[英]Rails Active Record cancel (save or create) within before_create callback without raising exception
Actually, I want to test a model callback. 实际上,我想测试一个模型回调。
system_details.rb (Model) system_details.rb(Model)
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
method is working fine and working as expected but it raises exception ActiveRecord::RecordNotSaved
when it returns false, and the exception breaks the rspec test
.what I want is, It should silently cancel save without raising an exception. prevent_if_same
方法工作正常并按预期工作但是当它返回false时引发异常ActiveRecord::RecordNotSaved
,并且该异常打破了rspec test
。我想要的是,它应该默默地取消保存而不引发异常。
system_detail_spec.rb (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
The 2nd test #callback
was failing because of exception. 第二次测试
#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
1)SystemDetail #callback确保不创建重复记录失败/错误:system_detail2 = create:system_detail,:similar_agent,user_id:user.id ActiveRecord :: RecordNotSaved:ActiveRecord :: RecordNotSaved
Is there any way to silently cancel save without raising an exception? 有没有办法在不引发异常的情况下默默取消保存?
I think in this case is better to use validate :prevent_if_same
because basically your method is kind of validation rule. 我认为在这种情况下最好使用
validate :prevent_if_same
因为基本上你的方法是一种验证规则。 Also it would prevent from creation silently. 它也可以防止静默创建。 You can always add error if you want to notify user about unsuccessful creation
如果要通知用户创建失败,可以随时添加错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.