首页 > 解决方案 > Minitest中“def setup”和“setup do”之间的区别?

问题描述

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

标签: ruby-on-railsrubyminitest

解决方案


还有另一个测试文件,其类定义为class FooTest < ActiveSupport::TestCase. 我想有人通过复制原始FooTest文件来创建它,却忘记更改名称。

简而言之,FooTest已经调用了 other 的 setup 方法而不是 this 。巧合的是,另一个在设置FooTest中也调用了相同create_three_users的方法,这就是为什么我在尝试分配实例变量但未能分配之前没有意识到这一点。

我找不到太多关于 and 之间实际区别的信息def setupsetup do但是一个博客(你必须相信我的话,因为它是用日语写的)写道,它setup do不仅调用了该类而且还调用了它的父类的设置过程,这可以解释为什么我的测试使用setup do(也许它称为setupfor both FooTests)。


推荐阅读