Last Updated: February 25, 2016
·
396
· davearonson

Retrieve new object from association, not class

When testing, you might do something like:

@user.make_widget
expect(Widget.last.color).to eql Widget.DEFAULT_COLOR

Don't. There might be some reason why the new widget isn't the "last" one, such as if the default sort order of Widgets is not chronological and there are other Widgets existing. (Yes, a test should start with a clean database, but on a recent project I had to run tests that were cleaned by transaction, and tests that were cleaned by truncation, against the same database. The last truncated test would leave its garbage in the database.) Instead, test:

@user.make_widget
expect(@user.widgets.last.color).to eql Widget.DEFAULT_COLOR

That way, preexisting widgets should not interfere, if you've forgotten to start with a clean database.