2013-02-02 138 views
0

你好我正在使用rspec來測試我的用戶模型。我只是想知道我在做什麼是測試中的常見做法。要測試錯誤消息我正在做這樣的事情Rails模型測試

User.create!(users(:first)) 
    user.update_attributes email: 'IDon\'tThinkThisIsAValidEmail' 
    user.should_not be_valid 
    assert user.errors.messages.include? :email 

另外我將如何去測試重複?調用full_messages並測試「電子郵件已被採納」的消息?這是一個很好的做法。我正在做這種測試,因爲在我的should_not be_valid測試通過之前,因爲用戶名無效,所以沒有用。是我在做什麼好主意?任何更好的測試方法?

回答

1

要驗證電子郵件的格式,您可以執行以下操作。請注意,您不必創建用戶記錄或使用Fixtures編寫大多數驗證規範。

it "will not allow invalid email addresses" do 
     user = User.new(email: 'notAValidEmail') 
     user.should have(1).error_on(:email) 
    end 

    it "will allow valid email addresses" do 
     user = User.new(email: '[email protected]') 
     user.should have(:no).errors_on(:email) 
    end 

爲了驗證存在,你可以這樣做:

it { should validate_presence_of(:email) } 

你可以看到更多的例子RSpec的文檔:

https://www.relishapp.com/rspec/rspec-rails/v/2-3/docs/model-specs/errors-on

2

你應該看看shoulda gem,它具有一套有用​​的測試斷言,包括獨特的驗證:

describe User do 
    should validate_uniqueness_of(:email) 
end 

編輯:Here's a link to the docs as a great place to start

+1

打我吧:)我也要去推薦文檔作爲開始的好地方http://rubydoc.info/github/thoughtbot/shoulda-matchers/master/frames –

+0

良好的調用,編輯添加。 – Winfield