Skip to content

Instantly share code, notes, and snippets.

@metaskills
Created July 19, 2011 20:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save metaskills/1093662 to your computer and use it in GitHub Desktop.
Save metaskills/1093662 to your computer and use it in GitHub Desktop.
class Merchant < ActiveRecord::Base
def foobarable?
# ...
end
end
class Customer < ActiveRecord::Base
belongs_to :merchant
def foobar=(something_else)
self[:foobar] = something_else if merchant.foobarable?
end
end
FactoryGirl.define do
factory :merchant do
end
factory :customer do
association :merchant
end
end
# How can I make sure that the merchant attribute/association is set first so
# that the foobar attribute checks my passed in merchant?
c = FactoryGirl.create :customer, :merchant => @some_merchant, :foobar => 'xyz'
@stephan-buckmaster
Copy link

Do two lines work?

c = FactoryGirl.create :customer, :merchant => @some_merchant
c.foobar = 'xyz'

@metaskills
Copy link
Author

Yes, but that should go without saying too. FYI, it would have to be broken up in a build then manual save. So something like this.

c = FactoryGirl.create(:customer, :merchant => @some_merchant).tap { |c| c.foobar = 'xyz' ; c.save! }

@metaskills
Copy link
Author

FWIW, here is the reason and talk around why.
thoughtbot/factory_bot#140

@stephan-buckmaster
Copy link

Looks to me your trouble with using Factory.create here shows that the corresponding Customer.create would also be unreliable (order matters, but Hash has no order).

@metaskills
Copy link
Author

Exactly, it does in 1.9 and that is also mentioned in the issue link.

@stephan-buckmaster
Copy link

I don't know if "that's a cure". Looks like asking for trouble: if someone isn't aware of the ordering requirement.

It seems to me when a Hash is accepted as an argument, then the message is that order is not important (in other languages too. of course).

@metaskills
Copy link
Author

I'm not disagreeing on that too, hence why I am using the patch till I hear other feedback from the authors.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment