我在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.我不知道为什么会收到此错误?
答案 0 :(得分:0)
您正在引用未正确设置的一对多关系。
def set_customer
@customer = current_member.company.customers.find(params[:customer_id])
end
此代码声明current_member属于拥有许多客户的公司。属于该公司的客户,请返回具有此ID的客户。
要实现此目的,您的customers表需要有一个名为company_id的外键。查看数据库迁移和this Rails guide。
还要将belongs_to添加到您的Customer类(首先执行此操作!并进行测试。这可能就是您所需要的。)
class Customers::AccountsController < ApplicationController
before_action :set_customer
belongs_to :company