thoughtbot/factory_girl — Issue #264: Using Factory's Model Instance Within Blocks?
Author: metaskills
Created: 2012-01-06 13:28:16+00:00
State: open

Till factory_girl 2.3.2 was released with the commit fba6f332 you could happily use the instance in lazy attribute blocks. For instance (no pun), given an model with a method `find_email` like so (uber contrived)

```ruby
class User < ActiveRecord::Base
def find_email
... # Contrived method that does something.
end
end
```

I could do something like this:

```ruby
factory :user do
email { find_email }
end
```

This now results in a `NoMethodError: undefined method 'find_email' for #<#:0x102ee9e10>` error. I was able to use this pattern in complex factories where a default association if left blank would build an object and I would use that object as the association key in other factory associations, like so. This is all broken now under 2.3.2 and master.

```ruby
factory :estimate do
association :dealer
customer { |e| e.association(:customer, :dealer => e.dealer) }
...
end
```

I realize I could use something like the `after_build` callback and that would indeed address my first contrived example. But in the case where factories are using instance methods to build associations in attribute order like the example above, by the time I get to `after_build`, the result of using the wring dealer could have propagated pretty far down the chain.

So my question is two fold. First, is it intentional that you no longer talk to the model instance in blocks or a by product of a code refactor and only testing attributes vs instance methods? Second, is there a proper way to talk to the object instance that I am not aware of or missed in the documentation/code? Based on these answers I could hopefully contribute a patch or something. Thanks in advance!