RSPEC nil:NilClass 的未定义方法 'jobs'(rails 上的ruby)

RSPEC undefined method 'jobs' for nil:NilClass (ruby on rails)

我正在用 RSPEC

测试我的控制器

控制器代码

class CustomersController < ApplicationController
  before_action :set_customer



  def jobs
    @jobs = @customer.jobs
  end



private 

  def set_customer
    if params[:id]
      @customer = Customer.find(params[:id])
    else
      @customer = Customer.find(params[:customer_id])
    end
  end

我的 Rspec 测试看起来是这样的:

测试代码

describe "GET job" do 
  it "renders the job view" do
     customer = FactoryGirl.create(:customer)
     controller.stub(:set_customer).and_return(customer)
     get (:jobs)
     expect(response).to render_template("customers/jobs.json.jbuilder")
  end
end

我得到的错误 - 它发生在调用 get(:jobs) 的过程中:

错误:

Failures:

  1) CustomersController assigns @jobs
     Failure/Error: get (:jobs)
     NoMethodError:
       undefined method `jobs' for nil:NilClass
        # ./app/controllers/customers_controller.rb:37:in `jobs'

我有另一个测试,但是那个在调用 get(:jobs) 时也给了我同样的错误。 我正在替换 set_customer 函数,并返回一个客户变量(由工厂女孩制作)。我不确定为什么它仍然未定义?作为参考(再次)控制器中此方法发生错误:

def jobs
  @jobs = @customer.jobs
end

如果这不是正确的方法,我如何生成一个 @customer 变量,就像它在控制器 set_customers 函数中所做的那样(通过参数)并将其传递给 rspec 测试?

您需要在请求调用中传入一个:id:customer_id参数值,例如:

get :jobs, id: 42

存根set_customer不设置实例变量,我想你甚至不需要存根,你已经有了实际的客户

describe "GET job" do 
  it "renders the job view" do
     customer = FactoryGirl.create(:customer)
     get(:jobs, id: customer)
     expect(response).to render_template("customers/jobs.json.jbuilder")
  end
end