Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between "def setup" and "setup do" in Minitest?

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
like image 216
reesaspieces Avatar asked Aug 14 '19 06:08

reesaspieces


1 Answers

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).

like image 154
reesaspieces Avatar answered Sep 18 '22 17:09

reesaspieces