Actually, I want to check the model callback.
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_samethe method works fine and works as expected, but it throws an exception ActiveRecord::RecordNotSavedwhen it returns false and the exception breaks rspec test. I want it to silently cancel the save without raising an exception.
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 #callbackfailed due to an exception.
Failures:
1) SystemDetail callback # ensures no duplicate entries Error / Error: system_detail2 = create: system_detail ,: similar_agent, user_id: user.id ActiveRecord :: RecordNotSaved: ActiveRecord :: RecordNotSaved
?