14

Are there any differences at all between calling def setup and setup do in Rails Minitests? I had been using def setup this whole time, but I suddenly found that my setup for a particular test file was not being called. When I changed it to setup do, it suddenly worked again (without changing anything else). But I find this very peculiar, and I'd rather stick to def setup for everything if possible, for consistency. Any advice is appreciated.

require 'test_helper'
require_relative '../../helpers/user_helper'

class FooTest < ActiveSupport::TestCase
  include UserHelper

  # This method doesn't get called as-is.
  # But it does get called if I change the below to `setup do`.
  def setup
    # create_three_users is a UserHelper method.
    create_three_users
    @test_user = User.first
  end


  test 'should abc' do
    # Trying to call @test_user here returned nil.
  end
end
reesaspieces
  • 1,600
  • 4
  • 18
  • 47

2 Answers2

10

There was another test file with the class defined as class FooTest < ActiveSupport::TestCase. I imagine someone created it by copying the original FooTest file, and forgot to change the name.

In short, the other FooTest's setup method had been getting called instead of this one. Coincidentally, the other FooTest had also been calling the same create_three_users in the setup, which was why I didn't realise this till I tried and failed to assign an instance variable.

I couldn't find much info on the actual difference between def setup and setup do, but one blog (you'll have to take my word because it's written in Japanese) writes that setup do calls the setup process for not only that class but also the its parent class, which might explain why my tests worked using setup do (maybe it called the setup for both FooTests).

Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
reesaspieces
  • 1,600
  • 4
  • 18
  • 47
3

From the Rails docs for ActiveSupport::Testing::SetupAndTeardown:

Adds support for setup and teardown callbacks. These callbacks serve as a replacement to overwriting the #setup and #teardown methods of your TestCase.

class ExampleTest < ActiveSupport::TestCase
 setup do
   # ...
 end

 teardown do
   # ...
 end
end

Which is likely a reference to Minitest's setup and teardown lifecycle hooks.

Jet Blue
  • 5,109
  • 7
  • 36
  • 48