2016-02-22 37 views
0

構建一個rails 4.2應用程序,我對TDD相當新,但我真的在學習它,我不知道爲什麼以下測試正在通過。測試通過時,它不應該不應該在條件驗證

def setup 
    @lead = Lead.new(first_name: "Joe", last_name: "Blow", email: "[email protected]", phone: "555 555 5555", 
      number_of_rooms: 5) 
end 
... 
... 

test "should have origin state if origin country is United States" do 
    @lead.origin_country_id = Country.create!(name: "United States").id 
    @lead.origin_state_id = nil 
    assert_not @lead.save 
end 

我的模型文件如下:

class Lead < ActiveRecord::Base 
    validates :origin_country_id, presence: true 
    validates :destination_country_id, presence: true 
    belongs_to :origin_state, class_name: 'State', foreign_key: 'origin_state_id' 
    belongs_to :destination_state, class_name: 'State', foreign_key: 'destination_state_id' 
    belongs_to :origin_country, class_name: 'Country', foreign_key: 'origin_country_id' 
    belongs_to :destination_country, class_name: 'Country', foreign_key: 'destination_country_id' 
end 

就像我說的,我是新來TDD,所以如果這是一個不好的測試,請讓我知道你將如何改善它。基本上,這被用來引用人們在國際上運送物品,所以我有一個起源國家和目的地國家,我需要驗證那些有國家的國家在提交數據時填寫了國家字段。國家是一個只有名字的模型,國家是一個具有國家ID且屬於一個國家的模型。

回答

0

您正在驗證origin_country_id的存在,但不存在origin_state_id。在您的測試中,您將值設置爲origin_country_id,但由於您未驗證origin_state_id,因此您要告訴Rails nil是該字段的可接受值。

+0

那麼如何在我的測試中隔離原產國,以確保國家是否存在,如果這個國家是美國呢? – user3562355

+0

這不是關於孤立國家。你根本不驗證狀態ID的存在。你有2個'validates'顯示,這兩個都不是'state'。 –

相關問題