2015-09-06 130 views
1

試圖測試一個模塊。它在rails控制檯中執行時有效,但在寫入測試時不起作用。假設以下幾點:如何測試Rails模型關聯

  1. 爲MyModel

    一個)的has_many:my_other_model

  2. MyOtherModel

    一個)屬於:my_model

模塊例如:

module MyModule 

    def self.doit 
    mine = MyModel.first 
    mine.my_other_models.create!(attribute: 'Me') 
    end 

end 

現在測試:

require 'test_helper' 

class MyModuleTest < ActiveSupport::TestCase 

    test "should work" do 
    assert MyModule.doit 
    end 

end 

返回:

NoMethodError: NoMethodError: undefined method `my_other_models' for nil:NilClass 

現在嘗試在控制檯同樣的事情:

rails c 

MyModule.doit 

作品就好了。但爲什麼不作爲測試?

+1

我認爲這個問題是你不創建測試前'MyModel'記錄,所以'.first'返回nil,我不知道你怎麼做,在MINITEST,但我想你谷歌可以檢查。 –

+0

謝謝穆罕默德!是的,問題是我的測試數據庫沒有記錄在dev db中。 –

回答

0

當您運行此測試時,您的測試數據庫爲空,因此調用MyModel.first將返回nil,然後嘗試將未知方法鏈接到nil。您可能需要的測試套件是fixture,這僅僅是示例數據。現在,您可以創建第一個實例來使測試正常工作。

test "should work" do 
    MyModel.create #assuming the model is not validated 
    assert MyModule.doit 
    end 

你也可以重構你的模塊。如果我的不是零,添加if mine將只嘗試創建其他模型。這將使測試通過,但否定了測試的目的。

def self.doit 
    mine = MyModel.first 
    mine.my_other_models.create!(attribute: 'Me') if mine 
    end 
+0

完美!謝謝。作爲新的rails我不知道rails控制檯默認爲開發數據庫,​​而測試去...測試分貝。 –