gpt4 book ai didi

ruby-on-rails - 当返回的消息为 'expect to raise_error' 时,为什么此 rspec 'ActiveRecord::RecordInvalid' 失败

转载 作者:行者123 更新时间:2023-12-03 23:47:16 25 4
gpt4 key购买 nike

以下 rspec 测试失败,但与失败测试一起提供的消息似乎是预期结果。

describe '#validate_maximum_pending_actions_not_been_reached' do
let(:action) { build :action, status: 'pending' }
before :each do
10.times do
create :action, status: 'pending'
end
end
it 'does not save the 11th action' do
expect(action.save).to raise_error #(ActiveRecord::RecordInvalid,'Validation failed: maximum number of pending actions already reached')
end
end


Failure/Error: let(:action) { build :action, status: 'pending' }
ActiveRecord::RecordInvalid:
Validation failed: maximum number of pending actions already reached

我已经尝试通过省略错误消息来降低具体性,并且只是期望测试会raise_error。测试仍然失败,但上面的描述表明确实出现了错误。

我做错了什么?

正在测试的方法如下:

validate :validate_maximum_pending_actions_not_been_reached
def validate_maximum_pending_actions_not_been_reached
errors[:base] << "maximum number of pending actions already reached" unless Action.where(status: 'pending').size <= 10
end

最佳答案

您的规范应该在这样的 block 中。此外,您还可以使用错误类指定错误

  it 'does not save the 11th action' do
expect{ action.save! }.to raise_error(ActiveRecord::RecordInvalid) #(ActiveRecord::RecordInvalid,'Validation failed: maximum number of pending actions already reached')
end

关于ruby-on-rails - 当返回的消息为 'expect to raise_error' 时,为什么此 rspec 'ActiveRecord::RecordInvalid' 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35455104/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com