2017-01-23 25 views
0

如何訪問在Minitest中的安裝方法中定義的變量?Ruby 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

您正在創建實例變量,然後期望它們存在於類上下文中。還有一個你缺少的操作順序問題:setup方法只有在類完全定義之後才運行,但是你立即行使這些變量來定義類。

如果您需要立即執行這些操作,請刪除setup do ... end塊。這也是更好地遵循紅寶石公約和定義它是這樣的:

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: ...這是一個命名關鍵字參數,應該省略。