【发布时间】:2015-04-27 19:23:56
【问题描述】:
我正在我的 Ruby on Rails 控制器上运行 RSPEC 测试,这是我正在测试的控制器操作:
控制器代码:
class Customers::AccountsController < ApplicationController
before_action :set_customer
def index
@accounts = @customer.accounts
respond_to do |format|
format.html
format.json
end
end
def set_customer
@customer = current_member.company.customers.find(params[:customer_id])
end
end
这是我的 RSPEC 测试代码:
before do
@member = FactoryGirl.create(:member)
@company = FactoryGirl.create(:company, owner_id: @member.id)
@customer = FactoryGirl.create(:customer_john_human,company_id:@company.id)
end
describe "GET INDEX" do
it "gets the index html page" do
get :index, {:customer_id=>@customer.id, :format=>:json}
end
end
错误:
ActiveRecord::RecordNotFound:
Couldn't find Customer with 'id'=1 [WHERE (`customers`.`company_id` IS NOT NULL) AND `customers`.`company_id` = ?]
# ./app/controllers/customers/accounts_controller.rb:87:in `set_customer'
# ./spec/support/engine_controller.rb:25:in `process_action'
# ./spec/support/engine_controller.rb:3:in `get'
# ./spec/controllers/customers/accounts_controller_spec.rb:21:in `block (3 levels) in <top (required)>'
我不确定customer.company_id = ? 是什么意思,如果我这样做:
puts @customer.inspect
我得到以下输出:
#<Customer id: 2, user_id: nil, title: nil, first_name: "John", last_name: "Kusu", created_at: "2015-04-27 18:42:00", updated_at: "2015-04-27 18:42:00", deleted_at: nil, company_name: nil, company_id: 6>
据我所知,company_id 已定义并设置为 6。我不确定为什么会出现此错误?
【问题讨论】:
-
你能显示加载current_member的代码吗?
-
堆栈跟踪中的错误通常不会真正显示测试中使用的真实公司 ID...但可能有一个。这 ?部分意味着你在某个地方有类似
where(company_id: 42)的东西,Rails 将其变成:where("company_id = ?", 42)有意义吗? -
现在.. 在你的控制器中你有这个:
current_member-> 那是什么?以及您的控制器将如何获得该当前成员?以及您在 rspec 中进行了哪些设置以确保当前成员实际登录。? -
请在您设置
Member和Company之间、Company和Customer之间的关联的模型中发布代码。Company中是否有多个外键引用Member,例如owner_id和member_id?
标签: ruby-on-rails testing rspec controller factory-bot