2015-02-11 29 views
0

我有一個驗證名稱和條款驗收RSpec的捕捉驗證錯誤

class Product < ActiveRecord::Base 

    validates :name, presence: true, 
      length: { maximum: 50 }, on: :update 

    validates_acceptance_of :agreed_to_terms, on: :update 

我寫了一個簡單的測試

it 'redirects back if there is missing info' do 
    post "/product/1", {:name => "john"} 

    expect(ActiveRecord).to raise_error(StatementInvalid) 
    end 

我似乎無法捕獲錯誤的模型。

ActiveRecord::StatementInvalid: 
    SQLite3::ConstraintException: NOT NULL constraint failed: 
+0

你確定這個錯誤實際上是提出?通常,驗證只是簡單地導致模型返回'false'來表示'valid?'。 – zetetic 2015-02-12 02:19:36

+0

驗證不會導致該錯誤被提出(當使用'save'時ActiveRecord :: RecordInvalid被提出 – 2015-02-12 07:01:04

回答

1

當你打電話的ActiveRecord不會觸發它,試試這個

it 'redirects back if there is missing info' do 
    expect { 
    post "/product/1", {:name => "john"} 
    }.to raise_error(ActiveRecord::StatementInvalid) 
end 
+0

但是如果我刪除驗證,它仍然會通過@Vimsha – softcode 2015-02-11 22:43:40

0

expect() raise_error是指()的代碼產生一個錯誤,很明顯。

你可以嘗試這樣。

expect{ 
    post "/product/1", {:name => "john"} 
}.to raise_error(StatementInvalid) 

順便說一句,我不認爲在控制器中測試模型驗證是個好主意。

+0

但是如果我刪除了驗證,它仍然會通過@ jerrytao – softcode 2015-02-11 22:44:21

+0

您需要提供更多信息,比如哪些列失敗的約束或關於您的模型的更多詳細信息,以及控制器中的參數。 – jerrytao 2015-02-12 12:17:51