加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails Active Record取消(保存或创建)before_c

发布时间:2020-12-17 01:57:07 所属栏目:百科 来源:网络整理
导读:实际上,我想测试一个模型回调. 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
实际上,我想测试一个模型回调.

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方法工作正常并且按预期工作但是当它返回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,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,user_id: user.id
ActiveRecord::RecordNotSaved:
ActiveRecord::RecordNotSaved

有没有办法在不引发异常的情况下默默取消保存?

解决方法

我认为在这种情况下最好使用validate:prevent_if_same,因为基本上你的方法是一种验证规则.它也可以防止静默创建.如果要通知用户创建失败,可以随时添加错误

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读