Reputation: 363
I'm setting up specs to test whether or not a job calls a method under certain conditions.
This is what I have so far:
describe RandomJob do
context "when payload[:type] = MyModel" do
let!(:my_model) { create :my_model }
let!(:payload) { { type: "MyModel", id: my_model.id } }
context "when Model exists" do
it "calls MyModel.fire! with payload" do
RandomJob.perform_now(payload)
expect_any_instance_of(MyModel).to receive(:fire!).with(payload)
end
end
context "when Model does not exist" do
it "does not call MyModel.fire!" do
RandomJob.perform_now(payload)
expect_any_instance_of(MyModel).not_to receive(:fire!)
end
end
end
end
Just to be sure my way of testing worked. I setup my job like this:
class RandomJob < ApplicationJob
def perform(payload)
@payload = payload
fire_model!
end
private
def fire_model!
my_model&.fire! @payload
end
def my_model
MyModel.find(@payload[:id])
end
end
I expected the first test to pass, and the second to fail. However, my first test is failing while the second is passing. What am I doing wrong?
Upvotes: 0
Views: 40
Reputation: 26758
You have to put the expectation before the perform_now
call.
context "when Model exists" do
it "calls MyModel.fire! with payload" do
expect_any_instance_of(MyModel).to receive(:fire!).with(payload)
RandomJob.perform_now(payload)
end
end
context "when Model does not exist" do
it "does not call MyModel.fire!" do
expect_any_instance_of(MyModel).not_to receive(:fire!)
RandomJob.perform_now(payload)
end
end
Upvotes: 2