2010-06-28 25 views
9

我使用了一些早該的RSpec匹配器來測試我的模型,其中之一是:早該rspec的匹配器:上=>:創建

describe Issue do 
    it { should_not allow_value("test").for(:priority) } 
end 

我對這個問題是我在我的模型驗證看起來是這樣的:

validates_format_of :priority, :with => /^(Low|Normal|High|Urgent)$/, :on => :update 

那麼運行這個測試時,我得到:

1) 'Issue should not allow priority to be set to "test"' FAILED 
    Expected errors when priority is set to "test", got errors: category is invalid (nil)title can't be blank (nil)profile_id can't be blank (nil) 

驗證不被觸發貝科使用它只能在更新上運行,我如何在更新和創建時使用這些shoulda匹配器?

回答

12

我認爲應該更好地處理這個問題。我遇到了這個問題,因爲我只想在創建新用戶時爲我的用戶模型運行唯一性驗證檢查。這是一個數據庫查詢,這樣做對更新的浪費,因爲我不允許用戶名進行更改:

validates :username, :uniqueness => { :case_sensitive => false, :on => :create }, 

幸運的,你可以解決這個問題通過明確界定了「主題」:

describe "validation of username" do 
     subject { User.new } 
     it { should validate_uniqueness_of(:username) } 
    end 

這種方法只對新實例進行測試。對於您的情況,您可能只需將主題更改爲已保存在數據庫中的內容,並設置了所有必要的字段。

+0

謝謝@endium。同樣,可以使用'subject {FactoryGirl.create(:user)}'來測試'on::update'-only驗證。 – scarver2 2015-02-23 14:50:33