實際上,我想測試模型回調。Rails Active Record在before_create回調中取消(保存或創建)而不會引發異常
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 test
,它應該默默取消保存而不會引發異常。
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
第2測試#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
有沒有什麼辦法可以默默取消保存而不會引發異常?
嗨@dziamber,謝謝你的答案。這裏我不想通知用戶有關創建失敗的情況,如果連續的前一個記錄相同,只想更新以前的記錄。 – Hrishi
所以我認爲使用'validate:prevent_if_same'會爲你工作 –
在'validate:prevent_if_same'的情況下,我必須強制添加一個錯誤來取消'save/create',否則記錄會被保存。添加錯誤將引發異常,並顯示已定義的錯誤消息,這是我不想要的。我只想優雅地跳過保存,沒有任何異常。 – Hrishi