【问题标题】:RSpec: How to write correct association in test for fixing error: ActiveRecord::RecordNotFoundRSpec:如何在测试中编写正确的关联以修复错误:ActiveRecord::RecordNotFound
【发布时间】:2021-02-21 11:26:03
【问题描述】:

我是编程新手,尝试编写测试但出现错误:

员工:

belongs_to :contact
belongs_to :account

帐户:

has_many :staff

联系

has_many :staff

我试着写

subject(:service) { SomeService.instance }
let(:room) { create(:chat) }
let(:account) { create(:account) }
let(:contact) { create(:contact) }
let(:consultant) { create(:staff, account: account).contact} 
# or i try to write something like this 
let(:consultant) { create(:staff, account_id: account.id, contact_id: contact.id)}

   context  do
      subject { service.call(account: account, consultant: consultant)}

      it { is_expected.to respond_to(:call).with_keywords(:account, :consultant)}
   end

错误:

consultant = account.staff.find_by!(contact_id: consultant.id)
ActiveRecord::RecordNotFound: 
Couldn't find Staff with [WHERE "staff"."account_id" = $1 AND "staff"."contact_id" = $2]

我认为我不了解一些基本的东西。请您给我一些建议好吗?

【问题讨论】:

  • 抱歉,我想我解决了这个问题:let(:consultant) { create(:staff, account: room.account).contact}

标签: ruby-on-rails rspec


【解决方案1】:

您的固定装置是使用 FactoryBot 还是 FactoryGirl?我在编写测试时遇到了这些问题,因为 RSpec 的文档并不是最好的。我建议您使用硬编写的固定装置,例如 Rails 在spec/fixtures 中为您创建的固定装置,然后当您了解测试数据库的工作原理时,您可以迁移回 FB/FG。这真的帮助我理解了发生了什么。

将灯具放在spec/fixtures/accounts.ymlspec/fixtures/contacts/yml 等文件中。然后在规范中,如果您添加夹具,它们将被加载到测试数据库中,您可以将它们用作规范中的变量,如下所示:

RSpec.describe "Some test" do
  fixtures :accounts
  fixtures :contacts

  context "test something" do
    let(:account_one) {accounts(:one)}
    let(:contact_one) {contacts(:one)}

    it "works" do
      # call variables like --> account_one
      ...
    end
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-31
    • 1970-01-01
    • 2011-11-10
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    相关资源
    最近更新 更多