如何为一个self.method创建rspec测试?

7

我当前在我的User类中有这个方法:

def self.authenticate(email, password)
  user = User.find_by_email(email)
  (user && user.has_password?(password)) ? user : nil
end

我该如何在此上运行rspec测试?
我尝试运行it { responds_to(:authenticate) },但我认为这里的self与authenticate不同。
作为rails的新手,我需要测试和关于self关键字的解释。谢谢!
2个回答

5
describe User do
  let(:user) { User.create(:email => "foo@bar.com", :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

1

@depa的回答很好,但为了提供其他选择并因为我更喜欢更短的语法:

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) { "foo@bar.com" }
      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

除了我对语法的偏爱外,我认为这种风格比其他风格有两个主要优点:
  • 它使覆盖某些值更容易(就像我上面用password所做的那样)
  • 更重要的是,它突出了什么没有被测试,例如空密码、不存在的用户等。
这就是为什么对我来说,使用contextsubject以及let的组合远比通常的风格优秀。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接