Test both with data and from a blank slate

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the testing category.

Last Updated: 2024-04-18

A lot of web development is interactive: you write some code then test it out in the browser locally. This is OK, especially in small projects, since not everything warrants integration tests (e.g. non-critical code used internally).

With that context in mind, I had the following code in my TasksController

def new
  # The idea is that there are usually very similar `Task`s, so it makes sense to
  # pre-populate the form with the data from the most recently created record. 
  @task = Task.initialize_with_previous_data
end

I tested this out in browser interactively and it seemed to work so I deployed.

However the form fields using the @tasks variable didn't render at all in production. This was because my interactive tests were in an environment where tasks were already in the database - however this feature started from blank in production.

Lesson

This is a common cause for bugs, so here's a prospective rule for avoiding it:

Test your code both: - with data; and - from a blank slate