【问题标题】:ACTIVE RECORD ERROR: Couldn't find Customer with 'id'=1 [WHERE (`customers`.`company_id` IS NOT NULL) AND `customers`.`company_id` = ?] RUBY ON RAILS活动记录错误:找不到“id”=1 的客户 [WHERE (`customers`.`company_id` IS NOT NULL) AND `customers`.`company_id` = ?] RUBY ON RAILS
【发布时间】: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 中进行了哪些设置以确保当前成员实际登录。?
  • 请在您设置MemberCompany 之间、CompanyCustomer 之间的关联的模型中发布代码。 Company 中是否有多个外键引用 Member,例如owner_idmember_id?

标签: ruby-on-rails testing rspec controller factory-bot


【解决方案1】:

您正在引用未正确设置的一对多关系。

  def set_customer
    @customer = current_member.company.customers.find(params[:customer_id])
  end

此代码表明 current_member 属于拥有许多客户的公司。在属于该公司的客户中,返回具有此 ID 的客户。

要实现这一点,您的客户表需要有一个名为 company_id 的外键。看看你的数据库迁移和this Rails guide

还将belongs_to 添加到您的Customer 类(首先执行此操作!然后进行测试。这可能就是您所需要的。)

class Customers::AccountsController < ApplicationController
  before_action :set_customer
  belongs_to :company

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-17
    • 1970-01-01
    • 2013-03-26
    • 1970-01-01
    相关资源
    最近更新 更多