我正在为控制器上下文编写规范:
控制器规格:
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
出于某种原因,上面的规范仍然返回
POST #update
错误/with invalid attributes
最佳答案
使用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/