在Rails Minitest中调用def setup
和setup do
有什么区别吗?我一直在使用def setup
,但是我突然发现我的特定测试文件的setup
没有被调用。当我将其更改为setup do
时,它突然又可以工作了(没有更改任何其他内容)。但我发现这很奇怪,为了一致性,我更愿意尽可能地坚持使用def setup
。任何建议都是值得感谢的。
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
发布于 2019-08-14 14:54:17
还有另一个测试文件,其类定义为class FooTest < ActiveSupport::TestCase
。我假设有人通过复制原始的FooTest
文件创建了它,但忘记了更改名称。
简而言之,另一个FooTest
的设置方法被调用了,而不是这个。巧合的是,另一个FooTest
在设置中也调用了相同的create_three_users
,这就是为什么我直到尝试分配一个实例变量时才意识到这一点。
我找不到太多关于def setup
和setup do
之间实际区别的信息,但一位blog (你必须相信我的话,因为它是用日语编写的)写道,setup do
不仅为那个类调用了设置过程,而且还为它的父类调用了设置过程,这可能解释了为什么我的测试使用setup do
(可能它对两个FooTest
都称为setup
)。
https://stackoverflow.com/questions/57489057
复制相似问题