Last Updated: February 25, 2016
·
291
· davearonson

Test count of association, not class

When testing, you might do something like:

expect { @user.make_widget }.to change { Widget.count }.by(1)

Don't. There might be some reason why the new widget's user_id doesn't get set. Instead, test:

expect { @user.make_widget }.to change { @user.widgets.count }.by(1)

That way you're only looking at the widgets that actually belong to the user.

1 Response
Add your response

If you've scoped your controllers to only return Widgets owned by the current user, an integration test should pick up a failure. But, then again, you should probably have authorization tests for that, and this definitely works in a unit test. Great tip!

over 1 year ago ·