Confused about 'reply_to' vs 'reply_to?'

I am learning Rails with railstutorial.org, and I'm confused with something: in this chapter the author tells us to do some testing in the console using the respond_to? method respond_to? User object, and it works fine. But later, when we write a test for the attribute :encrypted_password , it uses respond_to .

Out of curiosity, I tried respond_to in the console for the User object, and I get an error that the method does not exist. Alas, if I try to write a test using respond_to? instead of respond_to , the test does not run.

Can someone explain the difference to me, and why does the test only work with respond_to ?

+62
ruby-on-rails
Jul 27 '11 at 18:58
source share
3 answers

? Ruby considering ? and ! as valid characters in a method name. respond_to and respond_to? are different. ? indicates that this should be true or false (by agreement, this is not a requirement). In particular:

respond_to? is a Ruby method for determining whether a class has a specific method on it. For example,

 @user.respond_to?('eat_food') 

will return true if the User class has a eat_food method on it.

respond_to is a Rails method for responding to specific types of requests. For example:

 def index @people = Person.find(:all) respond_to do |format| format.html format.xml { render :xml => @people.to_xml } end end 

However, in the RailsTutorial link below, you see the RSpec should method, which interacts with the RSpec respond_to method. This will not be available on the console unless you run the rails console test .

+146
Jul 27 '11 at 19:09
source share

respond_to? is a boolean estimate. respond_to used (usually) to determine what information is displayed. More info here . respond_to? checks if the method exists and returns true if it is, and false if it is not.

+4
Jul 27 '11 at 19:04
source share

The test uses convenient assistants to be more convenient.

Ruby, so using old old respond_to? will work if you name it like this:

  @user.respond_to?(:encrypted_password).should be_true 

The controllers use another respond_to , but still have nothing to do with the ones you've already met.

+3
Jul 27 '11 at 19:04
source share



All Articles