2009-11-14 61 views
1

我在我的用戶模型中進行了此驗證。如何測試由Rails中的模型驗證拋出的自定義消息

validates_uniqueness_of :email, :case_sensitive => false, 
       :message => "Some funky message that ive cleverly written" 

在我的測試中,我希望確保當用戶進入我的消息肯定被所示的重複數據刪除電子郵件地址,但不必從上面複製錯誤字符串在我的測試。我不喜歡那樣,因爲我確信這個消息會隨着我開始考慮複製而改變。軌道是否存儲這些錯誤信息 - 我可以在我的測試中調用?

香港專業教育學院完成的

assert @error_messages[:taken] , user.errors.on(:email) 

一般的測試,但會通過任何其他電子郵件相關的錯誤的香港專業教育學院設置驗證了追趕IE不正確格式化,空白等

回答

2

我做了一個快速測試,它看起來像錯誤消息按您在您的模型類(自上而下)中編寫驗證語句的順序進行排序。

這意味着,你可以找到的第一個驗證錯誤信息上的錯誤排列在首位的屬性:

user.errors.on(:email)[0] 

因此,如果您的用戶模型類包含這樣的事情:

validates_presence_of :email 
validates_uniqueness_of :email, :case_sensitive => false, :message => "Some funky message that ive cleverly written" 
validates_length_of  :email 

...你會在user.errors.on(:email)[1]找到你的「時髦的消息」,但只有如果至少validates_presence_of觸發一個錯誤,太。

關於您的具體問題: 我能想到的在測試中重複你的錯誤消息的唯一方法,就是在你的用戶模型定義常量和使用,而不是直接鍵入消息該驗證:

EMAIL_UNIQUENESS_ERROR_MESSAGE = "Some funky message that ive cleverly written" 
... 
validates_uniqueness_of :email, :case_sensitive => false, :message => EMAIL_UNIQUENESS_ERROR_MESSAGE 

在您的測試,你可以使用這個常量,太:

assert_equal User::EMAIL_UNIQUENESS_ERROR_MESSAGE, user.errors.on(:email)[1] 
+0

感謝您的回覆。是的,我想過使用常量的可能性,只是想知道其他人做了什麼。感謝您的建議! – robodisco 2009-11-15 15:37:12

2

在rspec的,

it "should validate uniqueness of email" do 
    existing_user = User.create!(:email => email) 
    new_user = User.create!(:email => existing_user.email) 
    new_user.should_not be_valid 
    new_user.errors.on(:email).should include("Some funky message that ive cleverly written") 
end 
+0

感謝selva的代碼。這幾乎是我得到的,它的手冊輸入了我想要解決的錯誤信息。 – robodisco 2009-11-15 15:38:40