Skip to content

Commit

Permalink
Adding Criteria#first
Browse files Browse the repository at this point in the history
  • Loading branch information
Lar Van Der Jagt and Josh Graham authored and Pairing Workstation Nibbler committed Dec 28, 2009
1 parent 2a5d8e3 commit c0e920d
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
2 changes: 2 additions & 0 deletions lib/mongoid/criteria.rb
Expand Up @@ -341,6 +341,8 @@ def one
attributes ? @klass.instantiate(attributes) : nil
end

alias :first :one

# Adds a criterion to the +Criteria+ that specifies the fields that will
# get returned from the Document. Used mainly for list views that do not
# require all fields to be present. This is similar to SQL "SELECT" values.
Expand Down
32 changes: 31 additions & 1 deletion spec/unit/mongoid/criteria_spec.rb
Expand Up @@ -239,7 +239,37 @@

end

describe "#each_index" do
describe "#first" do

context "when documents exist" do

before do
@collection = mock
Person.expects(:collection).returns(@collection)
@collection.expects(:find_one).with(@criteria.selector, @criteria.options).returns({ :title => "Sir" })
end

it "calls find on the collection with the selector and options" do
criteria = Mongoid::Criteria.new(Person)
criteria.first.should be_a_kind_of(Person)
end

end

context "when no documents exist" do

before do
@collection = mock
Person.expects(:collection).returns(@collection)
@collection.expects(:find_one).with(@criteria.selector, @criteria.options).returns(nil)
end

it "returns nil" do
criteria = Mongoid::Criteria.new(Person)
criteria.first.should be_nil
end

end

end

Expand Down

0 comments on commit c0e920d

Please sign in to comment.