Ruby Minitest:访问设置方法中的变量

Ruby Minitest: Access variables in setup-method

如何访问在 Minitest 的设置方法中定义的变量?

require 'test_helper'

class TimestampTest < ActiveSupport::TestCase
  setup do
    @ag = AG.create(..., foo = bar(:foobar))
    @ap = AP.create(..., foo = bar(:foobar))
    @c  = C.create(..., foo = bar(:foobar))
  end

  [@ag, @ap, @c].each do |obj|
    test "test if #{obj.class} has a timestamp" do
      assert_instance_of(ActiveSupport::TimeWithZone, obj.created_at)
    end
  end
end

如果我运行这个@ag@ap@c都是nil。需要第 5-7 行的 bar(:foobar) 来访问夹具数据。

您正在创建实例变量,然后期望它们存在于 class 上下文中。您还缺少一个操作顺序问题: setup 方法仅在 class 完全定义后才为 运行,但您立即使用这些变量来定义 class.

如果您需要立即执行,请删除 setup do ... end 块。最好遵循 Ruby 约定并像这样定义它:

class TimestampTest < ActiveSupport::TestCase
  CLASSES = [
    AG,
    AP,
    C
  ]

  setup do
    @time_zones = CLASSES.map do |_class|
      [
        class.name.downcase.to_sym,
        _class.create(...)
      ]
    end.to_h
  end

  test "test if things have a timestamp" do
    @time_zones.each do |type, value|
      assert_instance_of(ActiveSupport::TimeWithZone, value.created_at)
    end
  end
end

请注意,您的 pseudo-code 和 (..., foo=...) 形式的方法调用无缘无故地创建了一个无关的变量 foo。这应该被省略,除非你的意思是 foo: ... 那是一个命名的关键字参数。