Skip to content

Commit

Permalink
Merge pull request mongodb#2082 from jonhyman/feature/update_findandm…
Browse files Browse the repository at this point in the history
…odify_docs_for_upsert

Updating comments for find_and_modify to say that :upsert is a valid option; adding specs.
  • Loading branch information
durran committed Jun 10, 2012
2 parents b8566e1 + 576aede commit 86726c4
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/mongoid/contextual/find_and_modify.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ class FindAndModify
#
# @option options [ true, false ] :new Return the updated document.
# @option options [ true, false ] :remove Delete the first document.
# @option options [ true, false ] :upsert Create the document if it doesn't exist.
#
# @since 3.0.0
def initialize(criteria, update, options = {})
Expand Down
1 change: 1 addition & 0 deletions lib/mongoid/contextual/mongo.rb
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ def explain
#
# @option options [ true, false ] :new Return the updated document.
# @option options [ true, false ] :remove Delete the first document.
# @option options [ true, false ] :upsert Create the document if it doesn't exist.
#
# @return [ Document ] The result of the command.
#
Expand Down
31 changes: 31 additions & 0 deletions spec/mongoid/contextual/find_and_modify_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,37 @@
}.to raise_error(Mongoid::Errors::DocumentNotFound)
end
end

context "when upserting" do

let(:criteria) do
Band.where(name: "The Mars Volta")
end

let(:context) do
described_class.new(criteria, { "$inc" => { likes: 1 }}, upsert: true)
end

let(:result) do
context.result
end

it "creates the document if it does not exist" do
expect {
result
}.to change{Band.where(name: "The Mars Volta").count}.from(0).to(1)
end

it "updates the document in the database if it does exist" do
the_mars_volta = Band.create(name: "The Mars Volta")

expect {
result
}.to_not change{Band.where(name: "The Mars Volta").count}

the_mars_volta.reload.likes.should eq(1)
end
end
end

context "when the selector does not match" do
Expand Down

0 comments on commit 86726c4

Please sign in to comment.