RSpec和Factory用于测试下一个,上一个记录 [英] RSpec and Factory for testing next, prev records
问题描述
我有一个User模型,该模型具有用于下一个和上一个用户的方法:
I have a User model which has methods for a next and previous user:
def next_user
User.where("id > ?", id).order("id ASC").first
end
def prev_user
User.where("id < ?", id).order("id DESC").first
end
我正在尝试使用RSpec和Factory girl进行测试以进行测试,并且不确定该方法-我只是开始使用TDD.
I'm trying to setup a test using RSpec and Factory girl to test this, and am not sure of the approach - i'm only getting started with TDD.
我正在尝试:
describe "previous_next" do
let(:user) { FactoryGirl.create(:user) }
let(:next_user) { FactoryGirl.create(:user) }
it "should know the next user" do
expect(user.next_user).to eq next_user
end
it "should know the previous user" do
expect(next_user.prev_user).to eq user
end
end
这是错误
1) User previous_next should know the next user
Failure/Error: expect(user.next_user).to eq next_user
expected: #<User id: 7624, name: "Example User", email: "sample9@email.com", created_at: "2013-01-13 04:31:19", updated_at: "2013-01-13 04:31:19", password_digest: "$2a$04$mbzI.yXYd9eSSfXbjChROewwvCHLFQI6qq5IUNzAKo9O...", remember_token: "KMSmiEeOr6f_Sgi8KJffIA", admin: false, plan_id: nil, password_reset_token: nil, password_reset_sent_at: nil, stripe_customer_token: nil>
got: nil
(compared using ==)
# ./spec/models/user_spec.rb:93:in `block (3 levels) in <top (required)>'
2) User previous_next should know the previous user
Failure/Error: expect(next_user.prev_user).to eq user
expected: #<User id: 7626, name: "Example User", email: "sample11@email.com", created_at: "2013-01-13 04:31:19", updated_at: "2013-01-13 04:31:19", password_digest: "$2a$04$uzrKmsXmVY7jUdRtfnfhUe89Jgy1176zE2UxdH90imJR...", remember_token: "gl10QvxjSMZYQS3JIgbREg", admin: false, plan_id: nil, password_reset_token: nil, password_reset_sent_at: nil, stripe_customer_token: nil>
got: nil
(compared using ==)
# ./spec/models/user_spec.rb:97:in `block (3 levels) in <top (required)>'
如果我将next_user记录创建为:user Factory的实例,为什么将其排空为nil?
If i'm creating the next_user record as an instance of the :user Factory, why is it evaulating to nil?
推荐答案
问题是let
懒惰地求值,直到您要求记录时,它才创建记录.
The problem is that let
lazily evaluates, it doesn't create the records until you ask for them.
使用let!
代替let
.急切地对它们进行评估,并在测试之前强制创建记录.
Use let!
instead of let
. That eagerly evaluates them and forces the records to be created before the test.
这篇关于RSpec和Factory用于测试下一个,上一个记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!