Common Rails Gotchas

Learn the Rails testing gotchas in detail.

We'll cover the following

Rails common testing gotchas

The following patterns in Rails lead to relatively silent test failure. We stumble over them all the time.

  • ActiveRecord models don’t save when we expect them to. The most common cause of this problem is that the creation of the object fails validation. Often this causes a test failure down the line because a record that was supposed to be found in the database isn’t there. That’s because it didn’t save. Using a factory tool helps with this, as does using save! and create! in the test, set up to have the failure happen at the point of the code problem and not further down the line.

  • In versions of Rails that use attr_accessible, Rails silently ignores inaccessible parameters in the mass assignment. Rails 5 will still ignore parameters not specified in a strong parameter permit command, but it’ll at least log them. This can lead to hours of fun as we try to figure out why that attribute, which is clearly part of the method call, is not part of the resulting object.

  • In integration tests, it’s common to forget to log in when required. This normally means anything we expect to be on the resulting page fails to show up. The save_and_open_page command is invaluable here since it’s sometimes hard to tease out what happened from the log. But save_and_open_page will clearly show us that we’re not logged in.

Get hands-on with 1200+ tech skills courses.