[英]RSPEC undefined method 'jobs' for nil:NilClass (ruby on rails)
Im testing my controller with RSPEC 我用RSPEC测试我的控制器
CONTROLLER CODE 控制器代码
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
My Rspec test looks like so: 我的Rspec测试看起来像这样:
TEST CODE 测试代码
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
The error I am getting - it happens during the call to get(:jobs) is: 我得到的错误-在调用get(:jobs)期间发生的错误是:
ERROR: 错误:
Failures:
1) CustomersController assigns @jobs
Failure/Error: get (:jobs)
NoMethodError:
undefined method `jobs' for nil:NilClass
# ./app/controllers/customers_controller.rb:37:in `jobs'
I have another test, but that one also gives me the same error when the call to get(:jobs) is made. 我进行了另一项测试,但是在调用get(:jobs)时,该测试也给了我同样的错误。 I am subbing out the set_customer function, and returning a customer variable (made via factory girl).
我正在取消set_customer函数,并返回一个客户变量(通过工厂女孩制作)。 I am not sure why it is still undefined?
我不确定为什么它仍未定义? For reference (again) the error is occurring for this method in the controller:
作为参考(再次),该方法在控制器中发生错误:
def jobs
@jobs = @customer.jobs
end
If this isn't the correct way to do this, how can i generate a @customer variable like its done in the controller set_customers function(via params) and pass it to the rspec test? 如果这不是执行此操作的正确方法,我如何生成@customer变量(如其在控制器set_customers函数中所做的那样)(通过params)并将其传递给rspec测试?
您需要将:id
或:customer_id
参数值传递给请求调用,例如:
get :jobs, id: 42
Stubbing set_customer
doesn't set the instance variable, I think you don't even need to stub, you already have the actual customer 存根
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.