thoughtbot/factory_girl — pull request #606 by oggy (2014-02-03 16:52:38+00:00)
Title: Add instance method to evaluator, so factories can access the object being built

Unless I'm missing something, there's no way to get access to the instance being built from inside the factory (inside a block that defines an attribute, that is). Which seems quite odd, because we already delegate method calls to this instance, so it's obviously present.

This tiny PR simply exposes the `instance` through an attribute reader.

## Use case

An ActiveRecord model that auto-creates an associated object on save. Let's say User will create a separate Profile object on save.

class User < ActiveRecord::Base
has_one :profile, inverse_of: :user

after_save :create_profile

def create_profile
(profile || build_profile).save!
end
end

A profile always needs a user linked to it. If we do this:

factory(:profile) do
user
end

Two profiles will be created with the same user_id (an error if you have a unique index).

I really want to create a profile which sets itself as the profile for the user:

factory :profile do
user { create(:user, profile: instance) }
end

Right now I can achieve this with `@instance`, but obviously seems brittle. Any harm in exposing this?