2014-03-05 178 views
0

我試圖在我的Rails 4應用程序上測試驗證。問題在於添加一個特定的驗證所有測試通過,而不管剩餘的驗證是否被評論。這裏是我的代碼:Ruby on Rails 4 testunit跳過驗證

# test/models/company_test.rb 
setup do 
    @company = companies(:one) 
    @company2 = companies(:two) 
end 

test "should not save company with invalid name" do 
    @company.name = "" 
    assert [email protected], "Saved company without name" 

    @company2.name = @company.name 
    assert [email protected], "Saved company without unique name" 

    @company.name = "a" 
    assert [email protected], "Saved company with shorter name than 2 characters" 

    @company.name = rand(36**65).to_s(36) 
    assert [email protected], "Saved company with longer name than 64 characters" 
end 

test "should not save company if website is invalid" do 
    @company.website = "foo" 
    assert [email protected], "Saved company with invalid website" 
end 

# app/models/company.rb 
validates :name, :owner_id, presence: true, uniqueness: true 
validates :name, length: { minimum: 2, maximum: 64 } 
validates :website, :format => URI::regexp(%w(http https)) 

現在,如果我註釋掉名稱驗證,所有測試仍然通過。然後,如果我也註釋掉網站驗證,那麼所有測試都會失敗。

回答

0

沒有找到有什麼錯這個特殊的代碼,但它周圍有:

我用從here正則表達式,並把它與Ruby on Rails guide定義格式驗證。

# app/models/company.rb 
validates :website, format: { with: /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w][email protected])?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w][email protected])[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/, message: "invalid url" }