Home > Software design >  How do I mock a callback in my FactoryGirl factory, using Rails 4.2.3?
How do I mock a callback in my FactoryGirl factory, using Rails 4.2.3?

Time:06-18

I’m using Rails 4.2.3. I have this callback in my user model …

after_create :publish
…
  def publish
    Mymodule::Publisher.new_user(user: self, x_forward: {})
  end

I would like to mock this callback

FactoryGirl.define do
    …

  factory :user do
    after(:build) do |user|
      allow(user).to receive(:publish)
    end

But this results in a

 The use of doubles or partial doubles from rspec-mocks outside of the per-test lifecycle is not supported.

When I run all tests where

create(:user)

What’s another way I can mock this callback in the factory?

CodePudding user response:

You can do it this way:

FactoryGirl.define do
  factory :user do
    # ... 
    after(:build) do |user|
      def user.publish
        # and here you can stub method response if you need
      end
    end
  end
end
  • Related