2010-06-09 50 views
0

我試圖測試模型的屬性與此格式:早該測試格式

# myapp/test/unit/comment_test.rb 
require 'test_helper' 

class CommentTest < ActiveSupport::TestCase 
    should_belong_to :article 

    should_validate_presence_of :name 
    should_validate_presence_of :email 
    should_validate_presence_of :content 
    should_validate_presence_of :article_id 

    should_not_allow_values_for :name, "123", "bob_y", "dave!" 
    should_allow_values_for :name, "Bob", "Joe Smith" 

    should_not_allow_values_for :email, "abc", "[email protected]", "[email protected]!d.com", "[email protected]" 
    should_allow_values_for :email, "[email protected]", "[email protected]", "[email protected]" 
end 


# myapp/app/models/comment.rb 
class Comment < ActiveRecord::Base 
    belongs_to :article 

    validates_presence_of :name 
    validates_presence_of :email 
    validates_presence_of :content 
    validates_presence_of :article_id 

    validates_format_of :name, :with => /\b[\w]+\b/i 
end 

我做了類似的排序在其他模型的驗證,它工作正常,但在這其中我得到這些錯誤:

2) Failure: 
test: Comment should not allow email to be set to "[email protected]". (CommentTest) 
[/Library/Ruby/Gems/1.8/gems/thoughtbot-shoulda-2.10.2/lib/shoulda/assertions.rb:67:in `assert_rejects' 
/Library/Ruby/Gems/1.8/gems/thoughtbot-shoulda-2.10.2/lib/shoulda/active_record/macros.rb:139:in `__bind_1276100388_113010' 
/Library/Ruby/Gems/1.8/gems/thoughtbot-shoulda-2.10.2/lib/shoulda/context.rb:351:in `call' 
/Library/Ruby/Gems/1.8/gems/thoughtbot-shoulda-2.10.2/lib/shoulda/context.rb:351:in `test: Comment should not allow email to be set to "[email protected]". ']: 
Expected errors when email is set to "[email protected]", got errors: name can't be blank (nil)name is invalid (nil)content can't be blank (nil)article_id can't be blank (nil) 

我得到這個每個測試應該使,我使用工廠女孩也如果那件事。

回答

2

您的評論模型未驗證電子郵件格式。你在做什麼沒有什麼問題,你的測試只是沒有通過,因爲你的代碼不適合測試通過。

添加電子郵件格式的驗證到您的評論類。

validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i 

然後你的測試應該通過。

+0

哇我不知道爲什麼我沒有看到,一定是工作得太晚。謝謝 – trobrock 2010-06-22 14:24:08