RSpec let方法在规范中使用时给出nil

时间:2012-05-22 12:37:54

标签: ruby-on-rails-3 rspec rspec2 ruby-on-rails-3.2 rspec-rails

当我运行此测试时

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

我明白了 失败:

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

为什么这是因为我用上面的let

定义了用户变量

1 个答案:

答案 0 :(得分:0)

如果你仔细观察,你会看到第5行的控制器发生的错误,而不是spec文件。使用let语句,一切都应该没问题。