<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Simone Carletti&#039;s Blog &#187; named_scope</title>
	<atom:link href="http://www.simonecarletti.com/blog/tags/named_scope/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.simonecarletti.com/blog</link>
	<description>Simone Carletti&#039;s personal ramblings on programming, syndication, search engines &#38; marketing.</description>
	<lastBuildDate>Tue, 07 Feb 2012 08:48:33 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Testing Rails: How to test Rails ActiveRecord Named Scopes</title>
		<link>http://www.simonecarletti.com/blog/2009/06/how-to-test-rails-activerecord-named-scopes/</link>
		<comments>http://www.simonecarletti.com/blog/2009/06/how-to-test-rails-activerecord-named-scopes/#comments</comments>
		<pubDate>Wed, 17 Jun 2009 07:37:55 +0000</pubDate>
		<dc:creator>Simone Carletti</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[activerecord]]></category>
		<category><![CDATA[named_scope]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://www.simonecarletti.com/blog/?p=392</guid>
		<description><![CDATA[How to effectively test ActiveRecord named scopes in Rails without querying the database.]]></description>
			<content:encoded><![CDATA[<p>One of my biggest deal when approaching new features in Rails is the correct answer to the question &#8220;<strong>how should I test this?</strong>&#8220;.</p>
<p>Someone would probably assert that <strong>everything you code can be tested</strong> and, even though I perfectly agree with that, I would probably be more interested in how that shiny piece of code can be tested. Rails made the creation of tests a piece of cake, but it&#8217;s not always so easy.</p>
<p>Have you ever tried to test the correct creation of a cookie in Rails 2.2? Have you ever written an helper test that involves routing rules in Rails 2.0? Have you ever created a test to ensure your caching strategy works as expected?</p>
<p>If you answered yes to at least to one of those questions, you probably know what I mean.</p>
<p>The first requirement to write effective tests is to <strong>know what you are playing with</strong>. You can&#8217;t really know how to test an ActiveRecord callback unless you don&#8217;t know how callbacks works in ActiveRecord and, off course, what your hook is supposed to do.</p>
<p>The second suggestion if you get stuck writing a test is to start reading how that feature or the underlying implementation has been tested in the original framework. So, if you need to write a test for your custom Rails <code>foo_tag</code> helper, you probably want to start reading how the Rails team tested the helpers available with the Rails framework. Believe me, you&#8217;ll discover tons of new features just reading the tests.</p>
<p>I don&#8217;t want to go deep further on how to write effective tests, I&#8217;m already writing something special about that topic. This time, let me show you how to test one of the most recent ActiveRecord features: <strong>named_scope</strong>.<span id="more-392"></span></p>
<h2>What are named_scope(s)?</h2>
<p>Named scopes have been introduced in Rails 2.1. Ok, this is probably not the very latest feature, but one of those I have been testing in the &#8220;wrong&#8221; way since a few weeks ago.</p>
<p>Named scopes enables you to define custom ActiveRecord filters to narrow down a database query without explicitly pass conditions or query options. You can also chain multiple scopes to get all the records matching the sum of all the conditions merged altogether.</p>
<p>Look the following example, taken from the great Ryan&#8217;s <a title="Ryan's Scraps: What's New in Edge Rails: Has Finder Functionality" href="http://ryandaigle.com/articles/2008/3/24/what-s-new-in-edge-rails-has-finder-functionality">What&#8217;s New in Edge Rails: Has Finder Functionality</a> blog post.</p>
<div class="codecolorer-container text default code-ruby" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /></div></td><td><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">class User &lt; ActiveRecord::Base<br />
&nbsp; named_scope :active, :conditions =&gt; {:active =&gt; true}<br />
&nbsp; named_scope :inactive, :conditions =&gt; {:active =&gt; false}<br />
&nbsp; named_scope :recent, lambda { { :conditions =&gt; ['created_at &gt; ?', 1.week.ago] } }<br />
end<br />
<br />
# Standard usage<br />
User.active &nbsp; &nbsp;# same as User.find(:all, :conditions =&gt; {:active =&gt; true})<br />
User.inactive # same as User.find(:all, :conditions =&gt; {:active =&gt; false})<br />
User.recent &nbsp; # same as User.find(:all, :conditions =&gt; ['created_at &gt; ?', 1.week.ago])</div></td></tr></tbody></table></div>
<h2>How to test named_scope(s) (the wrong way)</h2>
<p>Now that you know what named scopes are and how they works, at least on the surface, you probably want to know how to test them.</p>
<p>When I first started writing named scope tests, the most obvious way seemed to me to use fixtures. Unfortunately, my fixture files started to be cluttered by fake definitions quickly enough. Tons of records required just to test a single method.</p>
<div class="codecolorer-container text default code-ruby" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;height:300px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br />18<br />19<br />20<br />21<br />22<br />23<br />24<br /></div></td><td><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"># The following fixtures are used to test the Airport #best named_scope.<br />
# The value for search doesn't match current number of search instances<br />
# but it doesn't really matter in this case.<br />
<br />
&lt;% 10.times do |index| %&gt;<br />
initial_airport_code_ROM_&lt;%= index %&gt;:<br />
&nbsp; search: search_hotels_example<br />
&nbsp; custom_field: initial_airport_code<br />
&nbsp; value: ROM<br />
&lt;% end %&gt;<br />
<br />
&lt;% 5.times do |index| %&gt;<br />
initial_airport_code_FCO_&lt;%= index %&gt;:<br />
&nbsp; search: search_hotels_example<br />
&nbsp; custom_field: initial_airport_code<br />
&nbsp; value: FCO<br />
&lt;% end %&gt;<br />
<br />
&lt;% 5.times do |index| %&gt;<br />
initial_airport_code_RMA_&lt;%= index %&gt;:<br />
&nbsp; search: search_hotels_example<br />
&nbsp; custom_field: initial_airport_code<br />
&nbsp; value: RMA<br />
&lt;% end %&gt;</div></td></tr></tbody></table></div>
<p>Even worse, my code started to be overwhelmed by ugly precondition checks in order to ensure my test didn&#8217;t pass just because of inconsistent fixtures.</p>
<div class="codecolorer-container text default code-ruby" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br /></div></td><td><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">def test_recent_should_returns_latest_N_records_ordered_by_created_at<br />
&nbsp; # precondition: ensure the test doesn't pass<br />
&nbsp; # just because there are only 3 users.<br />
&nbsp; assert User.count &gt; 3<br />
<br />
&nbsp; users = User.recent(3).all<br />
&nbsp; assert_equal(3, users.length)<br />
&nbsp; assert_equal(User.find(:all, :limit =&gt; 3, :order =&gt; 'created_at DESC'), users)<br />
end</div></td></tr></tbody></table></div>
<p>Needless to say, the work to maintain all the fixtures was driving me crazy. I couldn&#8217;t believe that was the right way.</p>
<p><a title="Railscasts - Factories not Fixtures" href="http://railscasts.com/episodes/158-factories-not-fixtures">Then comes Factory</a>, and developers started to say factories are better than fixtures. I agree, at least you don&#8217;t have to deal with messy fixtures.</p>
<p>At this point I quickly decided to change my tests from the old fixture-school to the fashionable factory-style.</p>
<div class="codecolorer-container text default code-ruby" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;height:300px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br />18<br />19<br />20<br />21<br />22<br />23<br /></div></td><td><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">test &quot;named_scope :latest should return all bookmarks ordered by create_at DESC&quot; do<br />
&nbsp; Bookmark.delete_all<br />
&nbsp; bookmarks = (0..3).map { |t| Factory(:bookmark, :created_at =&gt; t.months.from_now) }<br />
&nbsp; assert_equal bookmarks.reverse, Bookmark.latest<br />
end<br />
<br />
test &quot;named scope :localized&quot; do<br />
&nbsp; Tutorial.delete_all<br />
&nbsp; one = Factory(:tutorial, :language =&gt; languages(:italian))<br />
&nbsp; two = Factory(:tutorial, :language =&gt; languages(:english))<br />
&nbsp; thr = Factory(:tutorial, :language =&gt; languages(:italian))<br />
<br />
&nbsp; assert_equal([one, thr], Tutorial.localized(languages(:italian)).all)<br />
end<br />
<br />
test &quot;named scope :published&quot; do<br />
&nbsp; Tutorial.delete_all<br />
&nbsp; one = Factory(:tutorial, :published =&gt; true)<br />
&nbsp; two = Factory(:tutorial, :published =&gt; false)<br />
&nbsp; thr = Factory(:tutorial, :published =&gt; true)<br />
<br />
&nbsp; assert_equal([one, thr], Tutorial.published)<br />
end</div></td></tr></tbody></table></div>
<p>Yeah, this code started to smell less than the previous one. Do you agree?</p>
<p>But there&#8217;s still something wrong with those tests. Ok they works and they are definitely better than the previous ones or than no tests at all. But there&#8217;s still an unnoticeable smell in the air. No, it&#8217;s not you, don&#8217;t worry.</p>
<p>The question is: <strong>Do you really need to use real active record instances?</strong> <strong>Do you really need to test against the database?</strong> No, you don&#8217;t and you probably won&#8217;t.</p>
<h2>How to test named_scope(s) (the right way)</h2>
<p>There&#8217;s a better way to test named scopes. You can write your tests to test the conditions generated by the named scope instead of the records returned by the query.</p>
<p>Let&#8217;s say you need to test the following named scopes.</p>
<div class="codecolorer-container text default code-ruby" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br /></div></td><td><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">class Video &lt; ActiveRecord::Base<br />
&nbsp; named_scope :localized, lambda { |language| { :conditions =&gt; { :language_id =&gt; language.id }}}<br />
&nbsp; named_scope :latest, lambda { |*args| { :limit =&gt; (args.shift || nil), :order =&gt; &quot;#{self.table_name}.created_at DESC&quot; }}<br />
end</div></td></tr></tbody></table></div>
<p>You already wrote these tests using the factory-way.</p>
<div class="codecolorer-container text default code-ruby" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;height:300px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br />18<br />19<br />20<br />21<br /></div></td><td><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">test &quot;named scope :localized&quot; do<br />
&nbsp; Video.delete_all<br />
<br />
&nbsp; one = Factory(:video, :language =&gt; languages(:italian))<br />
&nbsp; two = Factory(:video, :language =&gt; languages(:english))<br />
&nbsp; thr = Factory(:video, :language =&gt; languages(:italian))<br />
<br />
&nbsp; assert_equal([one, thr], Video.localized(languages(:italian)).all)<br />
end<br />
<br />
test &quot;named_scope :latest(N) should return latest(N) bookmarks ordered by created_at DESC&quot; do<br />
&nbsp; Video.delete_all<br />
&nbsp; videos = (0..3).map { |t| Factory(:video, :created_at =&gt; t.months.from_now) }<br />
&nbsp; assert_equal [videos[3], videos[2]], Video.latest(2)<br />
end<br />
<br />
test &quot;named_scope :latest should return all bookmarks ordered by created_at DESC&quot; do<br />
&nbsp; Video.delete_all<br />
&nbsp; videos = (0..3).map { |t| Factory(:video, :created_at =&gt; t.months.from_now) }<br />
&nbsp; assert_equal videos.reverse, Video.latest<br />
end</div></td></tr></tbody></table></div>
<p>You might be happy to know that there&#8217;s a really wonderful method, named <code>proxy_options</code>, that returns the options set by a named_scope.</p>
<div class="codecolorer-container text default code-ruby" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br /></div></td><td><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">p Video.latest.proxy_options<br />
# {:limit=&gt;2, :order=&gt;&quot;videos.created_at DESC&quot;}<br />
<br />
p Video.latest(2).proxy_options<br />
# {:limit=&gt;nil, :order=&gt;&quot;videos.created_at DESC&quot;}</div></td></tr></tbody></table></div>
<p>Isn&#8217;t that cool? Yeah, I know it is!</p>
<p>Now that we know how to get the query filters, we can use them to test our expectations.</p>
<div class="codecolorer-container text default code-ruby" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br /></div></td><td><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">test &quot;named scope :localized&quot; do<br />
&nbsp; expected = { :language_id =&gt; languages(:italian).id }<br />
&nbsp; assert_equal &nbsp;expected,<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Video.localized(languages(:italian)).proxy_options<br />
end<br />
<br />
test &quot;named_scope :latest(N) should return latest(N) bookmarks ordered by created_at DESC&quot; do<br />
&nbsp; expected = { :limit =&gt; 2, :order =&gt; &quot;videos.created_at DESC&quot; }<br />
&nbsp; assert_equal &nbsp;expected,<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Video.latest(2).proxy_options<br />
end<br />
<br />
test &quot;named_scope :latest should return all bookmarks ordered by created_at DESC&quot; do<br />
&nbsp; expected = { :limit =&gt; nil, :order =&gt; &quot;videos.created_at DESC&quot; }<br />
&nbsp; assert_equal &nbsp;expected,<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Video.latest.proxy_options<br />
end</div></td></tr></tbody></table></div>
<p>I you want to make your test even more cool, I&#8217;ve found a nice addition reading the <a href="http://github.com/thoughtbot/pacecar/">Thoughbot Pacecar</a> unit tests. You can add an initial <code>respond_to?</code> assertion to make sure you actually defined the named scope before testing it.</p>
<div class="codecolorer-container text default code-ruby" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br /></div></td><td><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">test &quot;named scope :localized&quot; do<br />
&nbsp; assert Video.respond_to?(:localized)<br />
&nbsp; expected = { :language_id =&gt; languages(:italian).id }<br />
&nbsp; assert_equal &nbsp;expected,<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Video.localized(languages(:italian)).proxy_options<br />
end</div></td></tr></tbody></table></div>
<p>Now that you know how to get access to the named scope options, should probably <strong>avoid wasting resources</strong> creating new records and running active record queries. <strong>Just because you are writing test it doesn&#8217;t mean you don&#8217;t need to care about performances or execution time.</strong></p>
<p>So far, this is the best way I found to test ActiveRecord named scopes. Do you know a better one?</p>
<p>Related posts<ol>
<li><a href='http://www.simonecarletti.com/blog/2009/08/user-profile-permalinks-with-ruby-on-rails-and-authlogic/' rel='bookmark' title='User profile permalinks with Ruby on Rails (and Authlogic)'>User profile permalinks with Ruby on Rails (and Authlogic)</a></li>
<li><a href='http://www.simonecarletti.com/blog/2010/07/the-way-to-rails-3/' rel='bookmark' title='The Road to Rails 3: make your Rails 2.3 project more Rails 3 oriented'>The Road to Rails 3: make your Rails 2.3 project more Rails 3 oriented</a></li>
<li><a href='http://www.simonecarletti.com/blog/2009/04/activerecordmulticonditions-development-discontinued/' rel='bookmark' title='ActiveRecord::MultiConditions development discontinued'>ActiveRecord::MultiConditions development discontinued</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.simonecarletti.com/blog/2009/06/how-to-test-rails-activerecord-named-scopes/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>

