How do you place an expectation that the correct ActiveRecord::Relation
is sent as a keyword argument? I've seen this sort of problem before, and in the past using hash_including
matcher resolves the issue, but not with ActiveRecord::Relation
. It is so frustrating because the error shows that there is no diff between the expectation and the actual received.
I have a spec that looks something like this:
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
and I get an error that looks like this:
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>'
As mentioned, trying to use hash_including
isn't helping. When the spec is changed to:
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
the diff becomes:
-["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>]>}]
It turns out match_array
matcher solves the problem in this case; which is pretty misleading because neither the expected nor actual is an 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