【问题标题】:RSPEC undefined method 'jobs' for nil:NilClass (ruby on rails)用于 nil:NilClass (ruby on rails) 的 RSPEC 未定义方法“作业”
【发布时间】:2015-04-20 03:31:57
【问题描述】:

我正在使用 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 测试?

【问题讨论】:

  • 查看binding.pry。在set_customer 中放置一个以查看它是否被执行,在jobs 中放置另一个以调查对象和参数

标签: ruby-on-rails testing rspec controller


【解决方案1】:

存根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

【讨论】:

  • @SUPERUSER 它应该与括号一起使用,唯一的问题是我在括号前放了一个空格,我会解决这个问题
【解决方案2】:

您需要将:id:customer_id 参数值传递给请求调用,例如:

get :jobs, id: 42

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-04
    • 1970-01-01
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多