I have model:
# encoding: utf-8
class Tag
include Mongoid::Document
field :name, type: String
field :count, type: Integer
index :name, unique: true
validates_uniqueness_of :name
def self.create_tag(name)
tag = Tag.new
tag.name = name
tag.count = 0
tag.save
end
def self.find_by_name(name)
Tag.where(name: name).entries
end
end
And I have test for the model:
describe Tag, "# simple database operations" do
it " - insert test records" do
Tag.create_tag("joe")
Tag.create_tag("joe")
p Tag.find_by_name("joe")
end
end
If I look at collection after test execution I’ll find only one record, but I want to catch exception in the case of duplicate record insertion.
Is it possible?
By default Mongoid writes in “fire and forget” mode. It sends a write and returns immediately. To check for error, you should write in “safe mode”. Try this.
Or, better yet,
See the doc here.