Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to test a named_scope that references a class attribute with Shoulda?
    primarykey
    data
    text
    <p>I have the following ActiveRecord classes:</p> <pre><code>class User &lt; ActiveRecord::Base cattr_accessor :current_user has_many :batch_records end class BatchRecord &lt; ActiveRecord::Base belongs_to :user named_scope :current_user, lambda { { :conditions =&gt; { :user_id =&gt; User.current_user &amp;&amp; User.current_user.id } } } end </code></pre> <p>and I'm trying to test the <code>named_scope :current_user</code> using <a href="http://shoulda.thoughtbott.com/" rel="nofollow noreferrer" title="Shoulda">Shoulda</a> but the following does not work.</p> <pre><code>class BatchRecordTest &lt; ActiveSupport::TestCase setup do User.current_user = Factory(:user) end should_have_named_scope :current_user, :conditions =&gt; { :assigned_to_id =&gt; User.current_user } end </code></pre> <p>The reason it doesn't work is because the call to <code>User.current_user</code> in the <code>should_have_named_scope</code> method is being evaluated when the class is being defined and I'm change the value of <code>current_user</code> afterwards in the <code>setup</code> block when running the test.</p> <p>Here is what I did come up with to test this named_scope:</p> <pre><code>class BatchRecordTest &lt; ActiveSupport::TestCase context "with User.current_user set" do setup do mock_user = flexmock('user', :id =&gt; 1) flexmock(User).should_receive(:current_user).and_return(mock_user) end should_have_named_scope :current_user, :conditions =&gt; { :assigned_to_id =&gt; 1 } end end </code></pre> <p>So how would you test this using <a href="http://shoulda.thoughtbott.com/" rel="nofollow noreferrer" title="Shoulda">Shoulda</a>?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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