CheeseFry CheeseFry - 7 months ago 66
Ruby Question

Factory Girl in MiniTest

I am piggybacking on my earlier question where I have a factory creating a parent and child. I am running my unit tests and have a simple one not passing.

test "invoice can save" do
invoice = build(:invoice)
assert invoice.save, "Error message: #{invoice.errors.full_messages}"
end


Returns the following error.


Error message: ["Trips can't be blank"]


But the following code works.

test "invoice can save" do
invoice = create(:invoice)
assert invoice.save, "Error message: #{invoice.errors.full_messages}"
end


My understanding is that
build
should be holding it in memory until save is called. Isn't the first a better test to see if it is successfully saving to the database?

Answer

Based on the Factory in your earlier question, you are calling before_create to set the trip. However, you are not creating the object, you're building it.

If you changed that before_create to an after_build it should resolve that persnickety test!

Here's a helpful link to an old article from Thoughtbots about the "callbacks" available in FactoryGirl