【发布时间】:2020-07-12 15:39:47
【问题描述】:
您如何期望正确的ActiveRecord::Relation 作为关键字参数发送?我以前见过这种问题,过去使用hash_including matcher 解决了这个问题,但没有ActiveRecord::Relation。这太令人沮丧了,因为错误表明期望值和实际收到的值之间没有 diff。
我有一个看起来像这样的规范:
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>]>}]
【问题讨论】:
-
试试
hash_including:with(hash_including(accounts: Account.where(id: incomplete.id)))。 -
@SebastianPalma 是的,这在这种情况下没有帮助。请参阅上面的更新输出。
-
抱歉,没看到。问题是 match 正在检查两个对象是否相同,而它们不是,除非您以某种方式将它们从 perform 方法传递给
ProcessAccounts.batch。ProcessAccountsJob是如何定义的?你用什么accounts在那里打电话给batch? -
看来
match_array是我这里需要做的。 -
从 Rspec-rails 5.0.2 -> 5.1.0 升级时随机遇到此错误,使用
hash_including修复了我的错误。
标签: ruby-on-rails ruby rspec rspec-rails