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
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 FooTest
s).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With