I currently have this method in my User
class:
def self.authenticate(email, password)
user = User.find_by_email(email)
(user && user.has_password?(password)) ? user : nil
end
How do I run rspec testing on this?
I tried to run it { responds_to(:authenticate) }
, but I assume the self thing is different from the authenticate.
I am still a beginner at rails and any tips on how to test and explanation on the self
keyword will be much appreciated!
describe User do
let(:user) { User.create(:email => "[email protected]", :password => "foo") }
it "authenticates existing user" do
User.authenticate(user.email, user.password).should eq(user)
end
it "does not authenticate user with wrong password" do
User.authenticate(user.email, "bar").should be_nil
end
end
@depa's answer is good, but for the sake of alternatives and because I prefer the shorter syntax:
describe User do
let(:user) { User.create(:email => email, :password => password) }
describe "Authentication" do
subject { User.authenticate(user.email, user.password) }
context "Given an existing user" do
let(:email) { "[email protected]" }
context "With a correct password" do
let(:password) { "foo" }
it { should eq(user) }
end
context "With an incorrect password" do
let(:password) { "bar" }
it { should be_nil }
end
end
end
end
Aside from my preference for the sytax, I believe this has 2 major benefits over the other style:
password
above)That's why the combination of using context
and subject
and let
is, for me, far superior to the usual style.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With