2016-03-12 13 views
0

我有一個共享兩個測試同一組斷言:如何重新軌之間的斷言測試

class MyControllerTest < ActionController::TestCase 

    test "send mail and save to db" do 
    ... 
    assert_equal 1, User.count 
    assert_equal 1, ActionMailer::Base.deliveries.size 
    assert_equal good_md5, Digest::MD5.hexdigest(attachment.decoded) 
    assert_response :success 
    ... 

    test "send mail and don't save to db" do 
    ... 
    assert_equal 0, User.count 
    assert_equal 1, ActionMailer::Base.deliveries.size 
    assert_equal good_md5, Digest::MD5.hexdigest(attachment.decoded) 
    assert_response :success 
    ... 
end 

我能做些什麼來重用這些說法,所以我不必贅述在每個測試?

assert_equal 1, ActionMailer::Base.deliveries.size 
assert_equal good_md5, Digest::MD5.hexdigest(attachment.decoded) 
assert_response :success 

我試圖把它們放入一個模塊,但我不能夠使用包括試塊中。

回答

0

我不知道它是否可以在ActionController :: TestCase中工作,但我傾向於將共享測試(和其他東西)放在我的文件末尾作爲獨立的方法,我可以從我的測試中調用。喜歡的東西:

class MyControllerTest < ActionController::TestCase 
    test "send mail and save to db" do 
     ... 
     test_values = HashWithIndifferentAccess.new 
     test_values[:user_count] = 1 
     test_values[:deliveries] = 1 
     test_values[:md5]  = good_md5 
     validate_values test_values 
    end 
    end 

    def validate_values(test_values) 
    assert_equal test_values[:user_count], User.count 
    assert_equal test_values[:deliveries], ActionMailer::Base.deliveries.size 
    assert_equal test_values[:md5], Digest::MD5.hexdigest(attachment.decoded) 
    assert_response :success 
    end 

有很多的變化 - 你可以在值只是給他們將在哈希代替,你可以contruct您的測試值,這樣你可以做在你的assert_equal一個循環,所以您只需寫一次等。

Anyhoo。希望有所幫助。