Sunday, February 4, 2018

Rspec and commit callback giving an incorrect result

Leave a Comment

I have a User and Role model:

class User < ApplicationRecord    has_and_belongs_to_many :roles   validates :roles, presence: true, on: :save   after_create_commit :assign_role    private    def assign_role     self.roles << Role.client if roles.empty?   end end  class Role < ApplicationRecord    has_and_belongs_to_many :users   validates :name, presence: true, uniqueness: true   scope :client, -> { where(name: :client) } end 

I can't get the following Rspec to pass:

  describe '#assign_role' do     context 'when creating a new user' do       it 'is triggered', test: true do         user = build(:user)         expect(user).to receive(:assign_role)         user.run_callbacks(:commit)       end     end   end (#<User id: nil, email: "tester1@example.com", created_at: nil, updated_at: nil>).assign_role(*(any args))  expected: 1 time with any arguments  received: 0 times with any arguments 

I know the method is nit being called because I put binding.pry inside the method.

However if I change the callback in the model to after_create and :create in the rspec test it works

describe '#assign_role' do     context 'when creating a new user' do       it 'is triggered', test: true do         user = build(:user)         expect(user).to receive(:assign_role)         user.run_callbacks(:create)       end     end   end 

I have even tried to turn off transactional tests with self.use_transactional_tests = false but it does not change the result. I want to use after_create_commit instead of after_create.

How can I get this test to pass?

rspec 3.7, rails 5.2.beta2

1 Answers

Answers 1

Please try this gem gem "test_after_commit" for that, You might be thinking, “That’s weird. Why do I have to use a whole separate gem to test a callback that comes with Rails? Shouldn’t it just happen automatically?”

You’re right. It is weird. But it won’t stay weird for long.

Once Rails 5 update, you won’t have to worry about test_after_commit.

please see this link

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment