0

SCENARIO
I have a named_scope on a model called 'last_week'. All it does is it fetches the records from last week.

I want to test this and my approach is to test that the results coming back are within a certain range. I don't know if this is the right way of testing this functionality on a class method.

I can't use RSpec, Shoulda or other 3rd party client plugin. I am only allowed to use Mocha if I want.

# Model

class Article < ActiveRecord::Base

  scope :last_week,   :conditions => { :created_at => 1.week.ago..DateTime.now.end_of_day }

end


#Test

class ArticleTest < ActiveSupport::TestCase

  test "named scope :last_week " do
    last_week_range = DateTime.now.end_of_day.to_i - 1.week.ago.to_i
    assert_in_delta last_week_range, Article.last_week.first.created_at - Article.last_week.last.created_at,  last_week_range
  end

end

Looking for feedback on what's right or wrong about this approach.

alenm
  • 1,013
  • 3
  • 15
  • 34

1 Answers1

1

First your scope is wrong: because code is executed on the fly your date range condition will depend on the time you booted your server...

Replace with:

scope :last_week,  lambda { :conditions => { :created_at => 1.week.ago..DateTime.now.end_of_day } }

Second, to test, I'd create some records and check if the scope get the proper ones:

  • create a factory

  • create two records

  • set created_at 1 week + 1 day ago for one record

  • check your scope only retrieves one (the proper one)

apneadiving
  • 114,565
  • 26
  • 219
  • 213
  • 1. Thanks for pointing out the lambda tip 2. So I am using fixtures and in my fixtures I know 3 records that are within the scope of :last_week. Is it bad to write the test like this `test "scope :last_week" do assert_equal 3, Article.last_week.count end` – alenm Aug 30 '12 at 21:59
  • Fixtires are not dynamic (unless you add ruby code inside), your test will fail next week + you must always check that your code does what you expect (find Entry in timeframe) AND rejects bad values (doesn't find entries outside timeframe) – apneadiving Aug 30 '12 at 22:07
  • I have some ruby code in the fixtures to have the dates appear dynamic for created_at: <%= DateTime.now %>. I guess I'm wondering if I can do what you mentioned with fixtures alone OR do I need to investigate a 3rd party plugin like FactoryGirl? – alenm Aug 30 '12 at 22:28
  • Make sure to use a gem like Timecop to freeze the time during the test or you'll get some strange failures in your automated test framework because the test ran exactly at midnight. – Dan Caddigan Dec 04 '13 at 19:14