thoughtbot / testing-rails

Source code for the Testing Rails book
Other
279 stars 49 forks source link

Clarify difference between FactoryGirl#build and ActiveRecord#new #52

Closed nathanielks closed 8 years ago

nathanielks commented 9 years ago

In the Instance Methods section of the book, you mention that you use FactoryGirl's build method because it doesn't persist the record to the database. You then mention you use ActiveRecord's new method because it also doesn't persist the record to the database. In my mind, there's no real reason to use FactoryGirl as both perform the same task, while one has less overhead (ActiveRecord).

Could you clarify the differences and advantages a bit more?

nathanielks commented 9 years ago

The Helper Specs section explains the reasoning more (we don't care about validity). Maybe add this to the Instance Methods section as well?

jsteiner commented 9 years ago

Sure @nathanielks! I'll follow up with the appropriate edits in the book, but I usually use build or build_stubbed when I want to set up a valid record. This may be because I plan on saving the object later in the test. I also may use them to take advantages of FactoryGirl's traits to set up multiple attributes at once. For example build(:user, :with_stripe_subscription) might set the stripe_customer_id and the stripe_subscription_id fields for me. If I don't care about the actual values of those fields, this is a nice abstraction.

I usually use ActiveRecord's new when I only care about one or two attributes and the record doesn't need to be valid. I find that this is almost always in a model spec testing something simple like this:

describe User, "#has_stripe_account?" do
  it "returns true if the customer id is present" do
    user = User.new(stripe_customer_id: "not blank")
    expect(user).to have_stripe_account
  end

  it "returns false if the customer id is nil" do
    user = User.new(stripe_customer_id: nil)
    expect(user).not_to have_stripe_account
  end
end
nathanielks commented 9 years ago

Boom! Thanks so much for clearing that up even further! I'm thoroughly enjoying the book, good job! :+1:

imwithsam commented 8 years ago

FWIW, I had this exact same confusion, and think it's worth clarifying in this section. Perhaps it just needs a footnote or reference to the section that later clarifies the difference.

jsteiner commented 8 years ago

Addressed in https://github.com/thoughtbot/testing-rails/pull/70. Let me know if there is any other way I can make this more clear.