Brandon Hansen
Brandon Hansen

Reputation: 826

RSpec Active Record Scope

I want to write a scope that requires that the start date of products be less than today. I wrote the following in rspec

it "Should not be found with a start date in the future" do
   @product.start_date = Date.tomorrow
   @product.save

   Product.active.find(@product.id).should == nil
end

That test fails, obviously. Then I wrote the scope-

scope :active, where('start_date <= ?', Date.today)

Then I rerun the spec and it fails with-

2) Product Should not be found with a start date in the future
 Failure/Error: Product.active.find(@product.id).should_not == true
 Couldn't find Product with ID=1 [WHERE (start_date <= '2010-12-20')]
 # ./spec/models/product_spec.rb:168:in `block (2 levels) in <top (required)>'

I cannot figure out how to get this code to pass. I do not want the product to be found.

Upvotes: 1

Views: 1328

Answers (1)

tokland
tokland

Reputation: 67850

Look at the error: "Couldn't find Product with ID=1", the scope is actually working. Problem is in your test, find raises an exception as usual because no record has been found. You either have to use find_by_id or assert the exception with rspec.

Upvotes: 3

Related Questions