【发布时间】: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