Matilda
Matilda

Reputation: 1718

Stub FactoryGirl Observer Class

I have a FactoryGirl as bellow. So I try to create few of the factoryGirl on the base block and inherit from it and depending on the test It stubs a method on Observer of the User class. The problem is once it stubs a method it keeps it stub for that class. as you can see we tried to unstub all the stubed at the beginning but since not all are always stubed we can't do that either. Any idea how to deal with this problem?

FactoryGirl.define do
 factory :base_user, class: User do |user|
     sequence(:email) {|n| "user#{n}@example.com" }
     password         'password'
     password_confirmation 'password'
     first_name       { 'Santa' }
     last_name        { 'Clause' }
    user.after_build do |u|
       [:after_create, :create_piick_user, :send_signup_email].each do |method|
        begin
          UserObserver.any_instance.unstub(method)
        rescue RuntimeError
        end
      end
    end
 end

factory :user, parent: :base_user do |user|
 user.after_build do |u|
       UserObserver.any_instance.stub(:after_create).and_return(nil)
     end
  end

  factory :user_with_welcome_email, parent: :base_user do |user|
    user.after_build do |u|
      UserObserver.any_instance.stub(:create_piick_user).and_return(nil)
    end
  end

end

Upvotes: 0

Views: 561

Answers (1)

andrewpthorp
andrewpthorp

Reputation: 5096

I wouldn't put the stub on the definition. On the definition you can just setup properties, then use

Factory.stub(:user)

Later on, which will stub all of the properties.

Upvotes: 1

Related Questions