Note that there are some explanatory texts on larger screens.

plurals
  1. PORSpec and stubbing parameters for a named scope
    text
    copied!<p>I'm try to write a spec for a named scope which is date dependent.</p> <p>The spec:</p> <pre><code>it "should return 6 months of documents" do Date.stub!(:today).and_return(Date.new(2005, 03, 03)) doc_1 = Factory.create(:document, :date =&gt; '2005-01-01') Document.past_six_months.should == [doc_1] end </code></pre> <p>The named scope in the Document model:</p> <pre><code>named_scope :past_six_months, :conditions =&gt; ['date &gt; ? AND date &lt; ?', Date.today - 6.months, Date.today] </code></pre> <p>The spec fails with an empty array, and the query in test.log shows why:</p> <pre><code>SELECT * FROM "documents" WHERE (date &gt; '2009-11-11' AND date &lt; '2010-05-11') </code></pre> <p>i.e. it appears to be ignoring my stubbed Date method.</p> <p>However, if I use a class method instead of a named scope then it passes:</p> <pre><code>def self.past_six_months find(:all, :conditions =&gt; ['date &gt; ? AND date &lt; ?', Date.today - 6.months, Date.today]) end </code></pre> <p>I would rather use the named scope approach but I don't understand why it isn't working.</p> <p>===</p> <p>In reply to @speicher:</p> <p>Thanks, but Timecop doesn't seem to help here.</p> <pre><code>it "should return 6 months of documents" do d = Date.new(2005, 03, 01) Timecop.travel(d) doc_1 = Factory.create(:document, :date =&gt; '2005-01-01') Document.past_six_months.should == [doc_1] end </code></pre> <p>Still passes for the class method approach but not for the named scope.</p> <p>I suspect that named_scope is doing some kind of manipulation on the passed conditions before actually evaluating them, meaning that Date.today is never called directly.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload