ree*_*ces 6 ruby ruby-on-rails minitest
调用def setup和setup doRails Minitests之间有什么区别吗?我一直在使用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
Run Code Online (Sandbox Code Playgroud)
ree*_*ces 10
还有另一个测试文件,其类定义为class FooTest < ActiveSupport::TestCase. 我想有人通过复制原始FooTest文件来创建它,但忘记更改名称。
简而言之,FooTest调用的是另一个的 setup 方法,而不是这个方法。巧合的是,另一个人FooTest也在设置中调用了相同的方法create_three_users,这就是为什么我直到尝试分配实例变量但失败后才意识到这一点。
我找不到关于def setup和之间实际差异的太多信息setup do,但是一个博客(你必须相信我的话,因为它是用日语写的)写道,setup do不仅调用该类的设置过程,还调用其父类的设置过程,这可能解释了为什么我的测试可以使用setup do(也许它setup为两个FooTest都调用了)。