Defining associated ids with FactoryGirl in a sane way

Posted . Visible to the public.

FactoryGirl.attributes_for doesn't honour associations defined in the factory so if you're submitting a user and you're sending along associated ids to create the associations it doesn't create the _id attribute.

Here's a simple solution that can be used as a controller macro in your controller specs - usually where this rears its head.

module ControllerMacros
def attributes_with_foreign_keys(*args)
FactoryGirl.build(*args).attributes.delete_if do |k, v|
["id", "type", "created_at", "updated_at"].member?(k)
end
end
end

RSpec.configure do |config|
config.include ControllerMacros, :type => :controller
end

You can use it like this:

https://gist.github.com/andyh/5c2fb114ef208986e34a

Andy Henson
Posted by Andy Henson to Foxsoft (2015-08-12 15:31)