I am currently following Michael Hartl’s tutorial on RoR and am trying to get to grips more with Rspec testing. I am able to follow the majority of what is going on however I am a bit confused as to what and how the :authenticate method functions:
it { should respond_to(:authenticate) }
And how it relates to the following section of code:
describe "return value of authenticate" do
before { @user.save }
let(:found_user) { User.find_by_email(@user.email) }
describe "with valid password" do
it { should == found_user.authenticate(@user.password) }
end
describe "with invalid password" do
let(:user_for_invalid_password) { found_user.authenticate("invalid") }
it { should_not == user_for_invalid_password }
specify { user_for_invalid_password.should be_false }
end
end
I understand the assignment a variable using let and the corresponding block, but I am struggling to understand what is happening when the authenticate method is called, what is it authenticating against in the initial line? Is it authenticating against the user.rb model that requires an email be present and that it matches a particular regex, or is it something else. I have included the user.rb code for clarity:
class User < ActiveRecord::Base
attr_accessible :email, :name, :password, :password_confirmation
has_secure_password
before_save { |user| user.email = email.downcase }
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
validates :password, length: { minimum: 6 }
validates :password_confirmation, presence: true
end
Any help much appreciated.
Without line numbers I might be misunderstanding which line you are referring to but here goes. The very first line of code you quote with the ‘respond_to’ method is merely asking the object whether it’s interface handles whatever you are asking it to respond to. I think there is a bit missing – it should be:
obj.should respond_to(:somemethod)It just checks that the object has a method with that name – so a fairly basic test.Your question about what is going on when you call the authenticate method might be explained by the fact that you can’t see the authenticate method in user.rb. In the older versions of the Hartl tutorial there is an authenticate method (I still have it on my machine 🙂
Looking at the way it is called in your code clearly it is implemented slightly differently off in a helper method or something… see the call to ‘has_secure_password’ in your model? That’s a helper method where :authenticate lives.
Check the source code/documentation for more details.