Question

I have an issue where the create method of FactoryGirl is not working as I would have thought it should. I have two example that I expect to do the same thing, but they don't.

Example 1

FactoryGirl.create(:subscription, contact: contact)

Example 2

FactoryGirl.build(:subscription, contact: contact).save

Additional snippets from my code

factory :subscription do        
    contact 
end

factory :contact do
    first_name   Faker::Name.first_name
    last_name    Faker::Name.last_name
    email_address Faker::Internet.email
end

Both examples run and create records in my tests. I check this by inspecting both objects after everything has run and check they have id's. However in my subscription class I am overriding the save method as below.

def save
    puts 'hello world'
    super
end

I would have expected factory_girl to call save and print out "hello world" since rails does. For example if I call the rails create or save method, it will print out "hello world". This has got me stumped.

Any help explaining why it does this is appreciated.

Was it helpful?

Solution

It looks like FactoryGirl uses the model's save! method, not save. Both of these methods directly call create_or_update (rather than save! calling save), so your custom save method is never executed.

OTHER TIPS

I had a similar issue, since we used Sequel instead of ActiveRecord. This is the error I've got:

 got #<NoMethodError: undefined method `save!' for

I've solved it in this way:

module FactoryGirl
  module Syntax
    module Methods

      def create(factory_name, params)
        build(factory_name, params).save
      end
    end
  end
end

RSpec.configure do |config|
  config.include FactoryGirl::Syntax::Methods
end

Maybe is not too fancy.. but is a short and very simple way to get it working.. For example:

my_model = create(:my_model, :username => 'billyidol')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top