cman77
cman77

Reputation: 1783

RSpec and Factory for testing next, prev records

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: "[email protected]", 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: "[email protected]", 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?

Upvotes: 2

Views: 240

Answers (1)

Daniel Evans
Daniel Evans

Reputation: 6818

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.

Upvotes: 2

Related Questions