当前位置:  开发笔记 > 后端 > 正文

为什么raise_error匹配器没有按预期工作?

如何解决《为什么raise_error匹配器没有按预期工作?》经验,为你挑选了1个好方法。

我正在为控制器POST #update/ with invalid attributes上下文编写规范:

控制器规格:

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



1> Jesus Castel..:

使用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

推荐阅读
我我檬檬我我186
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有