Reputation: 6263
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.
Upvotes: 0
Views: 1255
Reputation: 171
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')
Upvotes: 1
Reputation: 124419
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.
Upvotes: 2