MiniTest Default Variable Gotcha

My day to day is mostly spent working on a Ruby on Rails app. We use MiniTest as our test suite, and I learned something interesting about it today I wanted to share. Within each test, there is a default variable called name, that outputs the name of the test itself.

In my case, I was writing an integration test for a create function. Within that function, I was creating a new object that had an attribute called name. On my first pass writing the test, I wrote something like this:

test "create" do
title = "Name"
  post(
some_rails_path,
database_object: {
name: name,
other_attribute: "Your text here"
}
)
  assert_match "#{name} created.", response.body
end

You’ll notice in the code above, I set the variable title to a string value, but then in the rest of my code, I called a variable name in the post action and the assert_match . I didn’t notice this until I kicked off the test, but surprisingly, it passed.

Not knowing why it passed since I hadn’t set the variable name myself, I added puts name before the post action, and ran it again. The test passed of course, but interestingly, the output of the puts statement was “test_create”. Because MiniTest sets the variable name (which I didn’t realize at the time) to the name of the test, it was causing a false positive when I initially ran my test. Luckily I didn’t spend too much time figuring this out, but thought it was something worth sharing.


One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.