Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Already on GitHub? Sign in to your account

syntax methods with block #210

Closed
justinko opened this Issue Sep 28, 2011 · 5 comments

Comments

Projects
None yet
2 participants
Contributor

justinko commented Sep 28, 2011

Hi guys,

I always do this:

create(:person).tap do |person|
  person.posts.create
end

I would love to do this:

create(:person) do |person|
  person.posts.create
end

What do you think?

P.S. Thanks for all the hard work you've been putting into FG recently!

Owner

joshuaclayton commented Sep 28, 2011

This is interesting; typically, I'd do something like this:

FactoryGirl.define do
  factory :person do
    email

    factory :person_with_post do
      after_create do |person|
        person.posts.create
      end
    end
  end
end

I don't think the syntax change would be difficult to implement; it's more a concern that FG already supports this with callbacks. Thoughts?

Contributor

justinko commented Sep 28, 2011

The downside of the callbacks is you can't set attributes on the associated records/docs. "posts" in your example. And that would get really ugly when there are multiple associations being created.

I mainly use my proposal with RSpec's let:

let(:person) do
  create(:person) do |person|
    person.posts.create title: 'thoughtbot is rad'
    person.contacts.create(attributes_for(:contact)) do |contact|
      contact.email_addresses.create(address: 'foo@bar.com')
    end
  end
end

I love doing that type of setup vs person = create(:person)

@justinko justinko closed this Sep 30, 2011

Owner

joshuaclayton commented Sep 30, 2011

Did you want to reopen this issue? I'm digging this idea and would love to see a pull request. As far as I can tell, all it'd need is some tweaking to Factory::Syntax::Methods for build, create, and build_stubbed, as well as some tests to make sure it works for all three of these methods.

@justinko justinko reopened this Sep 30, 2011

Contributor

justinko commented Sep 30, 2011

Awesome. I'll send a pull request in the next couple days.

Owner

joshuaclayton commented Sep 30, 2011

sweet!

justinko added a commit to justinko/factory_girl that referenced this issue Oct 12, 2011

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