ruby-on-rails - 为什么 raise_error 匹配器没有按预期工作?

标签 ruby-on-rails ruby validation rspec

我正在为 Controller 编写规范 POST #update/具有无效属性 上下文:

Controller 规范:

context 'with invalid attributes' do
  it "does not change @foo's attributes with empty params" do
    expect(patch :update, id: @foo, foo: attributes_for(:foo,
                                                         start_time: nil,
                                                         end_time:   nil)
                                                       ).to raise_error('ActiveRecord::RecordInvalid')
  end
end

模型验证:

  validates :name, presence: true
  validate :dates_logic_validation

Foo 的日期逻辑自定义验证:

def dates_logic_validation
  if !start_time.present? || start_time.nil?
    errors.add(:start_time, "Please double check the starting time")
  elsif !end_time.present? || end_time.nil?
    errors.add(:end_time, "Please double check the starting time")
  elsif (start_time.to_datetime rescue ArgumentError) == ArgumentError
    errors.add(:start_time, 'Please double check the Start Time format')
  elsif (end_time.to_datetime rescue ArgumentError) == ArgumentError
    errors.add(:end_time, 'Please double check the End Time format')
  elsif start_time < Time.now
    errors.add(:start_time, 'Start time must be greater or equal to today\'s date')
  elsif start_time > end_time
    errors.add(:end_time, 'End time must be greater than start time')
  end
end

出于某种原因,上面的规范仍然返回 ActiveRecord 错误/Validation failed: Start time Please double check the starting time

最佳答案

在使用 raise_error 匹配器时,您需要将括号更改为花括号。

示例:

expect { raise "oops" }.to raise_error(RuntimeError)

来源:https://www.relishapp.com/rspec/rspec-expectations/v/3-1/docs/built-in-matchers/raise-error-matcher

关于ruby-on-rails - 为什么 raise_error 匹配器没有按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34386992/

相关文章:

javascript - 使用 jquery 更新特定类 div 中的文本

javascript - 注册时检查用户名唯一性

ruby-on-rails - 不确定如何生成 ECDSA 签名,给定私钥和消息

ruby - 将大文本粘贴到 Ruby 中的 Watir Webdriver 文本字段中

forms - 依赖于另一个字段的条件字段验证

javascript - JavaScript 中文本区域输入长度检查

ruby-on-rails - RSpec:为什么不让 work 而 before(:each) 呢?

ruby-on-rails - 用于设计的自定义注册 Controller 不覆盖创建操作

mysql - Ruby 和 MySQL : How to handle missing elements while parsing XML file

Angular - 表单生成器 - 表单控件无效未更新/ngIf 错误