ruby-on-rails - Rails Active Record 在 before_create 回调中取消(保存或创建)而不引发异常

标签 ruby-on-rails ruby activerecord rspec callback

实际上,我想测试一个模型回调。

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/

相关文章:

mysql - Rails `where` 时间少于查询

ruby - 为什么在此代码中需要 klass?

ruby-on-rails - 处理状态为已接受的唯一验证

ruby-on-rails - 为什么我的 Rails 应用程序中会出现使用 force_ssl 的无限重定向循环?

ruby-on-rails - 禁用 Rails 中的资源预编译功能

ruby-on-rails - ffmpegcarrierwave-video 总是返回 "unknown encoder libfaac"

ruby-on-rails - 如何使用 nginx 设置从 http 到 https 的重定向?

ruby-on-rails - 使用 Ruby on Rails 实现配对

ruby-on-rails - 用 :if 指定两个条件

ruby - Rails 3 db :migrate 的未定义方法 `visitor'