0

我无法弄清楚我在模型规范(user_spec.rb)中做错了什么。我正在尝试检查身份验证方法是否适用于有效密码,但User.find_by我认为规范的部分出现问题,因为它返回nil。我已经检查过它是否响应了 :authenticate、:password 和 :password_confirmation,它们都通过了(为了便于阅读,我将在下面的代码中省略它)。

这是我在运行规范时遇到的失败:

Failures:

  1) User return value of authenticate method with valid password should eq #<User id: 136, fullname: "Sherwood Hickle", email: "jewell.brekke@stokes.net", created_at: "2013-11-06 23:04:35", updated_at: "2013-11-06 23:04:35", password_digest: "$2a$04$O5V2X9sZrl/u2T9W25c3Pu/PU6XaIvtZSIB39Efkid6a...">
     Failure/Error: it { should eq found_user.authenticate(user.password) }

       expected: #<User id: 136, fullname: "Sherwood Hickle", email: "jewell.brekke@stokes.net", created_at: "2013-11-06 23:04:35", updated_at: "2013-11-06 23:04:35", password_digest: "$2a$04$O5V2X9sZrl/u2T9W25c3Pu/PU6XaIvtZSIB39Efkid6a...">
            got: #<User id: nil, fullname: nil, email: nil, created_at: nil, updated_at: nil, password_digest: nil>

       (compared using ==)

       Diff:
       @@ -1,2 +1,2 @@
       -#<User id: 136, fullname: "Sherwood Hickle", email: "jewell.brekke@stokes.net", created_at: "2013-11-06 23:04:35", updated_at: "2013-11-06 23:04:35", password_digest: "$2a$04$O5V2X9sZrl/u2T9W25c3Pu/PU6XaIvtZSIB39Efkid6a...">
       +#<User id: nil, fullname: nil, email: nil, created_at: nil, updated_at: nil, password_digest: nil>

     # ./spec/models/user_spec.rb:41:in `block (4 levels) in <top (required)>'

user_spec.rb:

require 'spec_helper'

describe User do

describe "return value of authenticate method" do
  user = FactoryGirl.create(:user)
  let(:found_user) { User.find_by(email: user.email) }

  describe "with valid password" do
    it { should eq found_user.authenticate(user.password) }
  end

  describe "with invalid password" do
    let(:user_for_invalid_password) { found_user.authenticate("invalid") }

    it { should_not eq user_for_invalid_password }
    specify { expect(user_for_invalid_password).to be_false }
  end
end

end

而且我还使用 FactoryGirl 生成用户名和电子邮件地址,但我认为这与失败没有任何关系:

require 'faker' 

FactoryGirl.define do 
  factory :user do |u| 
    u.fullname { Faker::Name.name } 
    u.email { Faker::Internet.email }
    u.password { "foobar" }
    u.password_confirmation { "foobar" }
  end 
end
4

1 回答 1

0

问题在于规范的设置方式。您正在使用一个隐式主题,对于本规范,它将是 User.new。这就是为什么您会看到一个具有所有 nil 属性的 User 对象。

你的 it 子句应该更像

it { found_user.authenticate(user.password).should eq user }

it { user_for_invalid_password.should be_nil }

这实际上测试了行为。

更新:

随着 RSpec 3.x 中引入期望语法作为首选语法,现在将是:

it { expect(found_user.authenticate(user.password)).to eq user }

it { expect(user_for_invalid_password).to be_nil }
于 2013-11-07T01:17:41.100 回答