我无法弄清楚我的模型规范(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
答案 0 :(得分:0)
问题在于规范的设置方式。你正在使用一个隐含的主题,对于这个规范,它将是User.new。这就是为什么你看到一个具有所有nil属性的User对象。
你的条款应该更像是
it { found_user.authenticate(user.password).should eq user }
和
it { user_for_invalid_password.should be_nil }
实际测试行为。
更新:
随着RSpec 3.x中使用expect语法作为首选语法,现在将是:
it { expect(found_user.authenticate(user.password)).to eq user }
和
it { expect(user_for_invalid_password).to be_nil }