【问题标题】:RSpec Catch Validation ErrorRSpec 捕获验证错误
【发布时间】:2015-02-11 21:55:55
【问题描述】:

我有一个模型可以验证名称和条款的接受度

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:

【问题讨论】:

  • 你确定这个错误是真的出现的吗?通常,验证只会导致模型为 valid? 返回 false
  • 验证不会引发该错误(使用save ActiveRecord::RecordInvalid 时会引发

标签: ruby-on-rails rspec rspec3


【解决方案1】:

试试这个

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

【讨论】:

  • 但是如果我删除验证,它仍然通过@Vimsha
【解决方案2】:

expect() raise_error 表示 () 中的代码会报错,显然调用 ActiveRecord 时不会触发。

你可以这样试试。

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

顺便说一句,我认为在控制器中测试模型验证不是一个好主意。

【讨论】:

  • 但是如果我删除验证,它仍然通过@jerrytao
  • 您需要提供更多信息,例如哪些列未通过约束或有关您的模型的更多详细信息。还有控制器中的参数。
猜你喜欢
  • 2015-08-06
  • 1970-01-01
  • 2012-05-17
  • 1970-01-01
  • 1970-01-01
  • 2016-11-20
  • 2018-03-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多