Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec Controller Testing - "assigns" behaving unexpectedly

I have built out a controller spec for my user model, and it passes, although I feel like it should fail. The spec is below:

describe UsersController do
  include Devise::TestHelpers

  let (:user) do
    FactoryGirl.create(:user)
  end
  let (:other_user) do
    FactoryGirl.create(:user)
  end

  before :each do
    @request.env["devise.mapping"] = Devise.mappings[:user]
    sign_in user
  end

  describe "#index" do
    it "can GET 'index'" do
      get :index
      response.should be_success
    end

    it "populates a list of users" do
      get :index
      expect(assigns(:users)).to eq([user])
    end
  end
end

The line "expect(assigns(:users)).to eq([user])" passes, but I feel like it should fail. After all, I've created two users (user and other_user) up at the top. I'm clearly misunderstanding what's going on, so can someone explain it?

like image 936
Bryce Avatar asked Sep 07 '12 14:09

Bryce


1 Answers

let is lazy; it won't create the user until the first time it's called (at which point the result is memoized). Since you call user but not other_user, only the first user is actually created, and the spec passes.

Use let! if you want eager evaluation, or make sure you call other_user somewhere.

RSpec Documentation

like image 152
John Avatar answered Oct 13 '22 11:10

John