Search code examples
ruby-on-rails-3rspecrspec2ruby-on-rails-3.2rspec-rails

RSpec let method gives nil when used in specs


When I run this test

require 'spec_helper'

describe AssignmentsController do

  let(:user) { create(:user) }
  let(:course) { create(:course) }

  describe "GET 'index'" do
     it "returns http success" do
      assignment = user.assignments.build(name: "Hello 2", start_date: "5/20/2000", due_date: "5/21/2000")
      get :index
      assigns(:assignment).should eq([assignment])
    end
  end
end

I get this Failure:

  1) AssignmentsController GET 'index' returns http success
     Failure/Error: get :index
     NoMethodError:
       undefined method `assignments' for nil:NilClass
     # ./app/controllers/assignments_controller.rb:5:in `index'
     # ./spec/controllers/assignments_controller_spec.rb:29:in `block (3 levels) in <top (required)>'

Why this be since I defined the user variable with lets above


Solution

  • If you look carefully, you'll see that the error originating from your controller on line 5, not the spec file. Everything should be fine with the let statement the way you have it.