RSpec and Factory for testing next, prev records

China☆狼群 提交于 2019-12-24 00:51:46

问题


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

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.

I'm trying this:

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

here is the error

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)>'

If i'm creating the next_user record as an instance of the :user Factory, why is it evaulating to nil?


回答1:


The problem is that let lazily evaluates, it doesn't create the records until you ask for them.

Use let! instead of let. That eagerly evaluates them and forces the records to be created before the test.



来源:https://stackoverflow.com/questions/14300685/rspec-and-factory-for-testing-next-prev-records

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!