2016-12-02 22 views
4

實際上,我想測試模型回調。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

有沒有什麼辦法可以默默取消保存而不會引發異常?

回答

0

我認爲在這種情況下最好使用validate :prevent_if_same,因爲基本上你的方法是一種驗證規則。它也會阻止默默的創作。你可以隨時添加錯誤,如果你想通知用戶關於創建不成功

+0

嗨@dziamber,謝謝你的答案。這裏我不想通知用戶有關創建失敗的情況,如果連續的前一個記錄相同,只想更新以前的記錄。 – Hrishi

+0

所以我認爲使用'validate:prevent_if_same'會爲你工作 –

+0

在'validate:prevent_if_same'的情況下,我必須強制添加一個錯誤來取消'save/create',否則記錄會被保存。添加錯誤將引發異常,並顯示已定義的錯誤消息,這是我不想要的。我只想優雅地跳過保存,沒有任何異常。 – Hrishi

相關問題