Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you create an rspec testing for a self.method?

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!

like image 363
George Tran Avatar asked Mar 29 '13 17:03

George Tran


2 Answers

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
like image 55
Marcelo De Polli Avatar answered Sep 19 '22 16:09

Marcelo De Polli


@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:

  • It makes it easier to override certain values (as I've done with password above)
  • More importantly, it highlights what hasn't been tested, e.g. a blank password, an user that doesn't exist etc.

That's why the combination of using context and subject and let is, for me, far superior to the usual style.

like image 32
ian Avatar answered Sep 18 '22 16:09

ian