2017-01-23 16 views
0

使用Rails創建模型的用戶名我創建的用戶模型:字符串email:字符串,然後我在user.rb寫了一些驗證(模型)模型試驗合格時,它不應該

class User < ApplicationRecord 
    validates :name, presence: true 
    validates :email, presence: true 
end 

和簡單的測試,這個模型

require 'test_helper' 

class UserTest < ActiveSupport::TestCase 
    def setup 
    @user = User.new(name: "John Cena", email: "[email protected]") 
    end 

    test "should be valid" do 
    assert @user.valid? 
    end 

    test "should not be valid" do 
    @user.name = "" 
    @user.email = "" 
    assert_not @user.valid? 
    end 
end 

一切都很好,但如果我評論1模型文件測試驗證線仍然通過。只有兩條線都有註釋,測試纔會失敗。我該怎麼做才能完成這個測試?我不想從這一個2測試。

+0

我不明白,你的測試有什麼錯誤?請將其粘貼 –

+0

問題在於,我不應該得到一個錯誤,當我應該。有斷言,但它不應該。 當我有 '類用戶 AbUndZu

+0

也許這是一些與春天緩存? try bin/spring stop – siegy22

回答

1

當測試模型驗證不只是斷言模型是有效的或無效的。它會引起誤報,並使其成爲測試需要滿足模型中每個驗證的要求 - 添加屬性或驗證意味着您需要重寫測試!

相反,您應該通過查看錯誤對象來驗證驗證是否存在。

class UserTest < ActiveSupport::TestCase 
    def setup 
    @user = User.new 
    @user.valid? 
    @messages = @user.errors.messages 
    end 

    test "validates name" do 
    assert_includes @messages[:name], "can't be blank" 
    end 

    test "validates email" do 
    assert_includes @messages[:email], "can't be blank" 
    end 
end 

您的功能和集成測試將覆蓋整個驗證 - 所以如果您滿足所有要求,則無需測試記錄是否有效。

相關問題