RSpec 尽管没有差异,但参数匹配期望失败

RSpec Fails argument match expectation despite no diff

如何期望将正确的 ActiveRecord::Relation 作为关键字参数发送?我以前见过这种问题,过去使用 hash_including 匹配器可以解决问题,但不能使用 ActiveRecord::Relation。令人沮丧的是,错误显示期望值与实际接收值之间没有 差异

我有一个看起来像这样的规格:

describe ProcessAccountsJob, type: :job do
  subject { described_class.new }
  let!(:incomplete) { create(:account, :incomplete_account) }

  it 'calls process batch service' do
    expect(ProcessAccounts).to receive(:batch).with(
      accounts: Account.where(id: incomplete.id)
    )
    subject.perform
  end
end

我收到如下错误:

  1) ProcessAccounts calls process batch service
     Failure/Error: ProcessAccounts.batch(accounts: accounts)

       ProcessAccounts received :batch with unexpected arguments
         expected: ({:accounts=>#<ActiveRecord::Relation [#<Account id: 14819, account_number: nil...solar: nil, pap: nil, types: [], annualized_usage: nil>]>})
              got: ({:accounts=>#<ActiveRecord::Relation [#<Account id: 14819, account_number: nil...solar: nil, pap: nil, types: [], annualized_usage: nil>]>})
       Diff:

     # ./app/jobs/process_accounts_job.rb:13:in `perform'
     # ./spec/jobs/process_accounts_job_spec.rb:9:in `block (2 levels) in <main>'

如前所述,尝试使用 hash_including 没有帮助。当规范更改为:

describe ProcessAccountsJob, type: :job do
  subject { described_class.new }
  let!(:incomplete) { create(:account, :incomplete_account) }

  it 'calls process batch service' do
    expect(ProcessAccounts).to receive(:batch).with(
      hash_including(accounts: Account.where(id: incomplete.id))
    )
    subject.perform
  end
end

差异变为:

       -["hash_including(:accounts=>#<ActiveRecord::Relation [#<Account id: 14822, account_number: nil, service_address: \"123 Main St\", created_at: \"2020-07-12 15:50:00\", updated_at: \"2020-07-12 15:50:00\", solar: nil, pap: nil, types: [], annualized_usage: nil>]>)"]
       +[{:accounts=>
       +   #<ActiveRecord::Relation [#<Account id: 14822, account_number: nil, service_address: "123 Main St", created_at: "2020-07-12 15:50:00", updated_at: "2020-07-12 15:50:00", solar: nil, pap: nil, types: [], annualized_usage: nil>]>}]

原来match_array匹配器解决了这个问题;这是非常误导的,因为预期和实际都不是数组。 ‍♂️

describe ProcessAccountsJob, type: :job do
  subject { described_class.new }
  let!(:incomplete) { create(:account, :incomplete_account) }

  it 'calls process batch service' do
    expect(ProcessAccounts).to receive(:batch).with(
      accounts: match_array(Account.where(id: incomplete.id))
    )
    subject.perform
  end
end