Ruby Minitest:在setup-method中访问变量

时间:2017-01-23 15:35:39

标签: ruby-on-rails ruby minitest

如何访问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)来访问夹具数据。

1 个答案:

答案 0 :(得分:2)

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

如果您需要立即执行,请删除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

请注意,您的伪代码使用(..., foo=...)形式的方法调用会无缘无故地创建一个无关的变量foo。除非你的意思是foo: ...,否则这应该被省略。这是一个命名关键字参数。