实际上,我想测试一个模型回调。
system_details.rb(模型)
class SystemDetail < ActiveRecord::Base
belongs_to :user
attr_accessible :user_agent
before_create :prevent_if_same
def agent
Browser.new(ua: user_agent, accept_language: 'en-us')
end
def prevent_if_same
rec = user.system_details.order('updated_at desc').first
return true unless rec
if rec.user_agent == user_agent
rec.touch
return false
end
end
end
prevent_if_same
方法工作正常并按预期工作,但它在返回 false 时引发异常 ActiveRecord::RecordNotSaved
,并且该异常中断了 rspec 测试
.我想要的是,它应该在不引发异常的情况下静默取消保存。
system_detail_spec.rb (rspec)
require 'rails_helper'
RSpec.describe SystemDetail, :type => :model do
context '#agent' do
it 'Checks browser instance' do
expect(SystemDetail.new.agent).to be_an_instance_of(Browser)
end
end
context '#callback' do
it 'Ensure not creating consecutive duplicate records' do
user = create :end_user
system_detail = create :system_detail, :similar_agent, user_id: user.id
updated_at = system_detail.updated_at
system_detail2 = create :system_detail, :similar_agent, user_id: user.id
system_detail.reload
expect(system_detail2.id).to be_nil
expect(system_detail.updated_at).to be > updated_at
end
end
end
第二个测试 #callback
由于异常而失败。
Failures:
1) SystemDetail#callback ensure not creating duplicate records Failure/Error: system_detail2 = create :system_detail, :similar_agent, user_id: user.id ActiveRecord::RecordNotSaved: ActiveRecord::RecordNotSaved
有什么方法可以在不引发异常的情况下静默取消保存吗?
最佳答案
我认为在这种情况下最好使用 validate :prevent_if_same
因为基本上你的方法是一种验证规则。它还会阻止静默创建。如果您想通知用户有关创建不成功的信息,您可以随时添加错误
关于ruby-on-rails - Rails Active Record 在 before_create 回调中取消(保存或创建)而不引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40934753/