I am trying to test a worker
in Rspec
using receive
. (This test in for my user.rb
model)
require 'rails_helper'
require 'cancan/matchers'
describe User, type: :model do
context 'when an user' do
subject(:ability) { Ability.new(user) }
let(:user) { create(:user, :user) }
it 'does not have admin role' do
expect(user.is_admin?).to be_falsey
end
it { is_expected.to be_able_to(:destroy, user) }
it 'has a profile when created' do
target = create(:user)
expect(target.profile).to be_present
end
it 'calls a worker when user is created' do
expect(CreateContactWorker).to receive(:perform_async).once(user_id, first_name, last_name, email)
end
end
end
This is where my worker is being called in my user.rb
model:
def create_contact
CreateContactWorker.perform_async(id, first_name, last_name, email)
end
Now, when testing this I get an error:
Failures:
1) User calls a worker when user is created
Failure/Error: expect(CreateContactWorker).to receive(:perform_async).once(user_id, first_name, last_name, email)
NoMethodError:
undefined method `receive' for #<RSpec::ExampleGroups::User "calls a worker when user is created" (./spec/models/user_spec.rb:43)>
Now, doing some research looks like receive
is a mocha
syntax? But what exactly is the difference between one and the rspec
syntax?
And of course, what am I doing wrong? Thanks for the help!!
CodePudding user response:
You need to allow the worker to receive calls, use the following.
it 'calls a worker when user is created' do
allow(CreateContactWorker).to receive(:perform_async)
subject
expect(CreateContactWorker).to have_received(:perform_async).with(user_id, first_name, last_name, email).once
end