<?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>Push cx &#187; tests</title>
	<atom:link href="http://push.cx/tag/tests/feed" rel="self" type="application/rss+xml" />
	<link>http://push.cx</link>
	<description>A traveling geek&#039;s blog on development, games, and the web</description>
	<lastBuildDate>Fri, 14 Oct 2011 10:24:13 +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>Why I Write Tests</title>
		<link>http://push.cx/2009/why-i-write-tests</link>
		<comments>http://push.cx/2009/why-i-write-tests#comments</comments>
		<pubDate>Tue, 13 Jan 2009 14:05:58 +0000</pubDate>
		<dc:creator>Peter Harkins</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[bugs]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[tests]]></category>

		<guid isPermaLink="false">http://push.cx/?p=421</guid>
		<description><![CDATA[I&#8217;ve had a few folks ask me if I really write tests for all my projects, like I mentioned in the last line of my second email in You&#8217;re Not Refactoring. Really? Really, even on personal projects. I write tests because I&#8217;m really good at writing buggy software. I&#8217;d bet I&#8217;m better than you. I&#8217;ve [...]]]></description>
			<content:encoded><![CDATA[<p>
I&#8217;ve had a few folks ask me if I really write tests for all my projects, like I mentioned in the last line of my second email in <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3B1c2guY3gvMjAwOS95b3VyZS1ub3QtcmVmYWN0b3Jpbmc=">You&#8217;re Not Refactoring</a>. <em>Really?</em>
</p>

<p>
Really, even on personal projects. I write tests because I&#8217;m really good at writing buggy software. I&#8217;d bet I&#8217;m better than you.
</p>

<p>
I&#8217;ve written those bugs that waste hours of time until I found the one missing (or added) bit of punctuation. I&#8217;ve written bugs that first-year programming students have caught. I&#8217;ve written so many of those really obvious bugs that my boss notices with the first glance that you&#8217;d be amazed I&#8217;ve never been fired. Bugs that confused my users into thinking they made mistakes. Bugs that ate data. Bugs that corrupt data silently. And lots of those little changes that broke that totally unrelated thing over there that, wait, yeah, it is actually related in this one tiny way. Bugs that would be really obvious if I&#8217;d remembered that one bug in IE6, if I&#8217;d remembered the API, if I&#8217;d remembered what my own code from last week looked like.
</p>

<p>
I write tests because I&#8217;m imperfect and I hate breaking things. I take code seriously and I&#8217;m happy when I write the best code I can. When I&#8217;m slipping in errors, when I&#8217;m wasting the time of myself and my users, and when I&#8217;m just plain afraid that I might be introducing bugs, I&#8217;m not writing good code. I don&#8217;t keep anything on my nightstand except my glasses, because I know I&#8217;m just going to knock it all off in the middle of the night when I&#8217;m groping for my glasses. I don&#8217;t want to set myself up to fail.
</p>

<p>
Testing <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3B1c2guY3gvMjAwNy9hZGVxdWFjeS1pcy1pbmFkZXF1YXRl">isn&#8217;t everything</a>, and I&#8217;ve talked about <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3B1c2guY3gvMjAwOC9ub3ctZG8teW91LWtub3ctaXQtd29ya3M=">its limits</a>. But it&#8217;s <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3B1c2guY3gvMjAwNy9wYWlubGVzcy11cGdyYWRlLXRvLXJhaWxzLTIw">saved my bacon</a> often enough that I feel like I&#8217;m taking needless risks when I don&#8217;t write tests.
</p>

<p>
Yeah, OK, <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3B1c2guY3gvMjAwOS90d2l0dGVyLWFuZC1ydWJ5cy1vcGVuLWNsYXNzZXM=">fun little one-off scripts</a> don&#8217;t have tests, but that script is also about the largest I&#8217;ll let code get without test. Read the comments, someone found that I left a bug lurking to shoot myself in the foot when I tried to expand or reuse the code.
</p>

<p>
I don&#8217;t want to write buggy software, but I know I will, so I write tests and then I build things that are far less buggy. I don&#8217;t test my personal projects out of a sense of obligation, I test them so I can relax and have fun building cool things.
</p>

<p>
That&#8217;s why my advice is always to start small with tests. Test what you can easily, you don&#8217;t have to write exhaustive tests that cover all possibilities on all your code. Write a happy-path test for when a function or method works right, and cover one or two ways things can go wrong or be misused. A few weeks or months from now when you break it in some silly way or don&#8217;t remember how it&#8217;s supposed to be called, the time you invested in tests will pay dividends. When some you narrow down a bug, write a test that exercises it, fix the bug, and smile as your test passes: that bug isn&#8217;t going to slip back into your code again. You&#8217;ll write better code without the stress. Trust me, I know.
</p> <img src="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=421" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://push.cx/2009/why-i-write-tests/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Painless Upgrade to Rails 2.0</title>
		<link>http://push.cx/2007/painless-upgrade-to-rails-20</link>
		<comments>http://push.cx/2007/painless-upgrade-to-rails-20#comments</comments>
		<pubDate>Thu, 13 Dec 2007 12:10:20 +0000</pubDate>
		<dc:creator>Peter Harkins</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[ActiveResource]]></category>
		<category><![CDATA[NearbyGamers]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[Rails 2.0]]></category>
		<category><![CDATA[routing]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[test]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[tests]]></category>
		<category><![CDATA[upgrade]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://push.cx/2007/painless-upgrade-to-rails-20</guid>
		<description><![CDATA[I spent a dead-easy 2.5 hours last night updating NearbyGamers to Rails 2.0. My svn commit message read (with links added here for convenience): Updated to Rails 2.0.1 rm&#8217;d lib/slash_urls.rb: Rails switched from ; to / to separate actions rm&#8217;d lib/resource_requirements.rb: now included in ActiveResources rm&#8217;d app/helpers/tags_helper.rb and gamers_helper.rb that had old controller names and [...]]]></description>
			<content:encoded><![CDATA[<p>
I spent a dead-easy 2.5 hours last night updating <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL05lYXJieUdhbWVycy5jb20=">NearbyGamers</a> to Rails 2.0. My svn commit message read (with links added here for convenience):
</p>

<blockquote>
Updated to Rails 2.0.1

<ul>
<li>rm&#8217;d <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3B1c2guY3gvMjAwNy9yYWlscy1zZW1pY29sb25zLW91dC1zbGFzaGVzLWlu">lib/slash_urls.rb</a>: Rails switched from ; to / to separate actions</li>
<li>rm&#8217;d <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2Rldi5ydWJ5b25yYWlscy5vcmcvdGlja2V0Lzc2MzMgd2l0aA0KCmh0dHA6Ly9wdXNoLmN4LzIwMDcvcmFpbHMtc2VtaWNvbG9ucy1vdXQtc2xhc2hlcy1pbgoK">lib/resource_requirements.rb</a>: now included in ActiveResources</li>
<li>rm&#8217;d app/helpers/tags_helper.rb and gamers_helper.rb that had old controller names and were unused anyways</li>
<li>app/controllers/gamers_controller.rb: documented and fixed raw post variable extraction</li><li>updated post_path linkers in many views, controllers, and tests</li>
<li>renamed discussion_anchor_post_path to anchor_discussion_post_path to match the new ordering for nested resource urls</li>
<li>fix tag sorting on <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL05lYXJieUdhbWVycy5jb20vdGFncw==">tag index</a></li>
<li>move tags from /tags/Board+Games to <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL05lYXJieUdhbWVycy5jb20vdGFncy9Cb2FyZF9HYW1lcw==">/tags/Board_Games</a>, as Rails fixed the bug that encoded &#8216; &#8216; as &#8216;+&#8217; in non-get variable parts of the URL</li>
</ul>
</blockquote>

<h2>The Details</h2>

<p>
The first two files I deleted were my patches to URL generation that Rails now includes. The next two helper files I never used, but had had old (singular noun) names.
</p>

<p>
The bit about documentation: the way to get at raw post variables changed, so I tweaked code and left myself a reminder of why I&#8217;m doing it (I had to look at the changelog, which means it wasn&#8217;t self-evident).
</p>

<p>
Nested resources (I have nested <kbd>map.resources :discussions { |d| d.resources :posts }</kbd>) changed from <kbd>discussion_edit_post_url</kbd> to <kbd>edit_discussion_post_url</kbd>, so there was a bunch of places to change that. The next change about anchor is me following this convention with my own convenience method.
</p>

<p>
Tag sorting on the index page was a bug that Snarky pointed out to me. When I made some performance tweaks to that page I forgot to keep sorting tags as they came out of the database. This arguably should&#8217;ve been a revision of its own as it&#8217;s unrelated to the upgrade, but it was an easy one-line bugfix so I let it in.
</p>

<p>
Last, I renamed the tag pages. The tag model&#8217;s <kbd>to_param</kbd> just returns <kbd>self.name</kbd> and Rails would turn &#8220;Board Games&#8221; into &#8220;Board+Games&#8221;. It&#8217;s common but technically incorrect, as + only means space in encoded GET/POST variables. The proper encoding of &#8220;Board%20Games&#8221; was really noisy, so I took a page from Wikipedia&#8217;s pagebook and use underscores instead, like &#8220;Board_Games&#8221;. Was one line in the <kbd>to_param</kbd> and one line in the controller&#8217;s <kbd>load_tag</kbd> before_filter, a dozen lines of tweaking old tests, and seven lines of new tests. Eeeeeasy. 
</p>

<h2>The Verdict</h2>

<p>
Tests, tests, tests. If I didn&#8217;t have a solid test suite, I&#8217;d be noticing bugs two months from now in the least-frequently-exercised bits of code. Not only would I not have remembered to test some of the functionality, I wouldn&#8217;t have remembered the corner cases &#8212; or maybe I&#8217;d just have gotten bored of clicking through pages over and over and ignored the corner cases.
</p>

<p>
None of these were hard fixes and none were frustrating. I&#8217;d probably have finished even sooner if I hadn&#8217;t also been poking <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2ljYW5oYXNjaGVlemJ1cmdlci5jb20vMjAwNy8xMi8xMS9taXRvc2lzLw==">lolcats</a> and chatting with friends. And now I have a big list of shiny new Rails 2.0 features I can put to work in <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL05lYXJieUdhbWVycy5jb20=">NearbyGamers</a>.
</p> <img src="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=292" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://push.cx/2007/painless-upgrade-to-rails-20/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mocha</title>
		<link>http://push.cx/2007/mocha</link>
		<comments>http://push.cx/2007/mocha#comments</comments>
		<pubDate>Sat, 18 Aug 2007 19:41:31 +0000</pubDate>
		<dc:creator>Peter Harkins</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Mocha]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[tests]]></category>

		<guid isPermaLink="false">http://push.cx/2007/mocha</guid>
		<description><![CDATA[I posted yesterday that I was dropping my own little custom mocking code and considering Mocha. A few hours later I made a pass at it and was blown away. It took very little time to convert my ~600 lines of tests to use Mocha and I spent most of that time just cleaning out [...]]]></description>
			<content:encoded><![CDATA[<p>
I <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3B1c2guY3gvMjAwNy9zaW1wbGUtcnVieS1tb2NraW5n">posted yesterday</a> that I was dropping my own little custom mocking code and considering Mocha. A few hours later I made a pass at it and was blown away. It took very little time to convert my ~600 lines of tests to use Mocha and I spent most of that time just cleaning out the cruft that my mocking code had engendered.
</p>

<p>
I&#8217;m now a big fan of Mocha like I am <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3B1c2guY3gvMjAwNy9yYWlscy0xMjEtaW1wcmVzc2lvbg==">of Rails</a>. Ruby has a way of allowing coders to write magically polished libraries.
</p> <img src="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=254" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://push.cx/2007/mocha/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Simple Ruby Mocking</title>
		<link>http://push.cx/2007/simple-ruby-mocking</link>
		<comments>http://push.cx/2007/simple-ruby-mocking#comments</comments>
		<pubDate>Fri, 17 Aug 2007 20:15:29 +0000</pubDate>
		<dc:creator>Peter Harkins</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[dependency injection]]></category>
		<category><![CDATA[mocking]]></category>
		<category><![CDATA[mocks]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[tests]]></category>
		<category><![CDATA[unit tests]]></category>

		<guid isPermaLink="false">http://push.cx/2007/simple-ruby-mocking</guid>
		<description><![CDATA[I mentioned at the end of my last post on testing that I wrote some code to do mocking for my unit tests in Ruby. Writing a small mock library was very much reinventing the wheel, but I needed to do it to earn a deeper understanding of mocks. I&#8217;m writing some code (&#8220;Fetcher&#8221;) to [...]]]></description>
			<content:encoded><![CDATA[<p>
I mentioned at the end of my <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3B1c2guY3gvMjAwNy9maXh0dXJlcy1pbi1ydWJ5LXVuaXQtdGVzdHM=">last post on testing</a> that I wrote some code to do mocking for my unit tests in Ruby. Writing a small mock library was very much reinventing the wheel, but I needed to do it to earn a deeper understanding of mocks. 
</p>

<p>
I&#8217;m writing some code (&#8220;Fetcher&#8221;) to talk to a POP3 server, fetch mail, and pass it off to another process. One of the tests deals with what happens when the POP3 server is down or otherwise unreachable.
</p>

<pre>&nbsp;
def test_setup_server_down
  pop3 = Mock.<span style="">new</span>
  pop3.<span style="">expect</span><span style="color: #66cc66;">&#40;</span>:<span style="color: #000000; font-weight: bold;">new</span>, <span style="color: #66cc66;">&#91;</span>MAIL_SERVER, MAIL_POP3_PORT<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span> raise Timeout::<span style="color: #006600;">Error</span>.<span style="">new</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">"execution expired"</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#125;</span>
  f = Fetcher.<span style="">new</span><span style="color: #66cc66;">&#40;</span>pop3<span style="color: #66cc66;">&#41;</span>
  <span style="color: #808080; font-style: italic;"># further assertions that f acts correctly</span>
<span style="color: #b1b100;">end</span></pre>

<p>
This says that the Mock object expects a call to the new method with the given arguments, and when the call happens it runs the block. The block could return anything, but in this case it raises the same error as <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5ydWJ5LWRvYy5vcmcvc3RkbGliL2xpYmRvYy9uZXQvcG9wL3Jkb2MvY2xhc3Nlcy9OZXQvUE9QMy5odG1s">Net::Pop3</a> does when it can&#8217;t contact the server. After that the test can go on to make whatever assertions it needs to verify that the exception was handled properly.
</p>

<p>
The Mock object has a list of <kbd>calls</kbd> it expects to see and keeps a list of how it&#8217;s been <kbd>called</kbd> (yes, this could just be one list with an index but I thought it was mentally simpler this way). The test sets up what calls it should <kbd>expect</kbd> to see with what arguments (or blank for any) and block to run (or blank for none). When a method is called on the mock object, <kbd>method_missing</kbd> logs the call and executes the given block (raising a fuss if the call didn&#8217;t match what it expected). 
</p>

<pre>&nbsp;
class Mock
  attr_reader :calls, :called
&nbsp;
  <span style="color: #808080; font-style: italic;"># the stub arg makes it just record all calls</span>
  def initialize
    <span style="color: #0000ff;">@calls</span> = <span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span>
    <span style="color: #0000ff;">@called</span> = <span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span>
  <span style="color: #b1b100;">end</span>
&nbsp;
  <span style="color: #808080; font-style: italic;"># Pass nil for args to ignore the actual args in the call.</span>
  <span style="color: #808080; font-style: italic;"># Proc is optional; default is empty proc returning nil.</span>
  def expect<span style="color: #66cc66;">&#40;</span>method, *args, &amp;proc<span style="color: #66cc66;">&#41;</span>
    <span style="color: #0000ff;">@calls</span> &lt;&lt; <span style="color: #66cc66;">&#123;</span>:method =&gt; method, :args =&gt; args.<span style="">first</span>, :proc =&gt; <span style="color: #66cc66;">&#40;</span>proc <span style="color: #b1b100;">or</span> Proc.<span style="">new</span><span style="color: #66cc66;">&#123;</span><span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#125;</span>
  <span style="color: #b1b100;">end</span>
&nbsp;
  def method_missing<span style="color: #66cc66;">&#40;</span>method, *args<span style="color: #66cc66;">&#41;</span>
    <span style="color: #0000ff;">@called</span> &lt;&lt; <span style="color: #66cc66;">&#123;</span>:method =&gt; method, :args =&gt; args<span style="color: #66cc66;">&#125;</span>
&nbsp;
    expect = <span style="color: #0000ff;">@calls</span>.<span style="">shift</span>
    raise <span style="color: #ff0000;">"Unexpected mock call #{method.to_s}(#{args.join(', ')})"</span> <span style="color: #b1b100;">if</span> expect.<span style="">nil</span>?
    raise <span style="color: #ff0000;">"Wrong mock call #{method.to_s}(#{args.join(', ')}); expected #{expect[:method]}(#{expect[:args].join(', ')})"</span> <span style="color: #b1b100;">if</span> method != expect<span style="color: #66cc66;">&#91;</span>:method<span style="color: #66cc66;">&#93;</span> <span style="color: #b1b100;">or</span> <span style="color: #66cc66;">&#40;</span>expect<span style="color: #66cc66;">&#91;</span>:args<span style="color: #66cc66;">&#93;</span> != nil <span style="color: #b1b100;">and</span> args != expect<span style="color: #66cc66;">&#91;</span>:args<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span>
    expect<span style="color: #66cc66;">&#91;</span>:proc<span style="color: #66cc66;">&#93;</span>.<span style="">call</span><span style="color: #66cc66;">&#40;</span>*args<span style="color: #66cc66;">&#41;</span>
  <span style="color: #b1b100;">end</span>
end</pre>

<p>
It&#8217;s a straightforward little object, and I also added some code to raise a fuss if expected calls weren&#8217;t made. This does have the downside that any tests defining their own <kbd>teardown</kbd> need to call <kbd>super</kbd>.
</p>

<pre>&nbsp;
class Mock
  def fail_if_not_empty
    <span style="color: #808080; font-style: italic;"># Empty the call stack so that this obj doesn't throw errors for</span>
    <span style="color: #808080; font-style: italic;"># every later test between now and this object getting gc'd</span>
    calls, <span style="color: #0000ff;">@calls</span> = <span style="color: #0000ff;">@calls</span>, <span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span>
    raise <span style="color: #ff0000;">"Mock calls uncalled: n"</span> + calls.<span style="">collect</span> <span style="color: #66cc66;">&#123;</span> |call| <span style="color: #ff0000;">"#{call[:method]}(#{call[:args]} { #{call[:proc] })"</span> <span style="color: #66cc66;">&#125;</span>.<span style="">join</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">" "</span><span style="color: #66cc66;">&#41;</span> <span style="color: #b1b100;">unless</span> calls.<span style="">empty</span>?
  <span style="color: #b1b100;">end</span>
end
&nbsp;
class Test::<span style="color: #006600;">Unit</span>::<span style="color: #006600;">TestCase</span>
  def teardown
    finish_mocks
  <span style="color: #b1b100;">end</span>
&nbsp;
  def finish_mocks
    ObjectSpace.<span style="">each_object</span><span style="color: #66cc66;">&#40;</span>Mock<span style="color: #66cc66;">&#41;</span> <span style="color: #b1b100;">do</span> |m|
      <span style="color: #000066;">m</span>.<span style="">fail_if_not_empty</span>
    <span style="color: #b1b100;">end</span>
  <span style="color: #b1b100;">end</span>
end</pre>

<p>
This has been a handy piece of code to test the code I&#8217;ve written in the last two weeks, but it&#8217;s not good enough. I have to use a technique called dependency injection to test <kbd>Fetcher.new</kbd>, where the outside code passes it a POP3 object instead of its <kbd>initialize</kbd> just using Net::POP3. Useful for testing, but my code is badly repetitive when all the instantiation calls have to do this exact same setup. (As an aside, Jacob Proffitt recently started an interesting conversation on <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3NjcnVmZnlsb29raW5nY2F0aGVyZGVyLmNvbS9hcmNoaXZlLzIwMDcvMDgvMDcvZGVwZW5kZW5jeS1pbmplY3Rpb24uYXNweA==">dependency injection</a>, took <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3NjcnVmZnlsb29raW5nY2F0aGVyZGVyLmNvbS9hcmNoaXZlLzIwMDcvMDgvMTUvcmlwcGluZy1vbi1kaS5hc3B4">criticism</a>, and <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3NjcnVmZnlsb29raW5nY2F0aGVyZGVyLmNvbS9hcmNoaXZlLzIwMDcvMDgvMTYvdGlsdGluZy1hdC13aW5kbWlsbHMuYXNweA==">responded</a>. Good reading.)
</p>

<p>
I was pondering how to extend the Mock object to let me mock class methods (eg a call to <kbd>Net::POP3.new</kbd>) when I realized I&#8217;d gone as far as I should down the do-it-yourself road. I&#8217;d heard of <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL21vY2hhLnJ1Ynlmb3JnZS5vcmcv">Mocha</a> and it took me all of ten minutes to think to look at its <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2NoZWF0LmVycnRoZWJsb2cuY29tL3MvbW9jaGEv">cheat sheet</a> where that&#8217;s the first example.
</p>

<p>
After spending two hours or so writing and tweaking this code, the best thing for it is to be thrown away. I&#8217;ve learned about mocking by doing it and I&#8217;m better-prepared to understand someone else&#8217;s larger and better library.
</p> <img src="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=253" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://push.cx/2007/simple-ruby-mocking/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Fixtures in Ruby Unit Tests</title>
		<link>http://push.cx/2007/fixtures-in-ruby-unit-tests</link>
		<comments>http://push.cx/2007/fixtures-in-ruby-unit-tests#comments</comments>
		<pubDate>Thu, 12 Jul 2007 21:45:47 +0000</pubDate>
		<dc:creator>Peter Harkins</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[fixtures]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[tests]]></category>
		<category><![CDATA[unit tests]]></category>

		<guid isPermaLink="false">http://push.cx/2007/fixtures-in-ruby-unit-tests</guid>
		<description><![CDATA[I&#8217;m writing some Ruby scripts that sort and store lots of small files. After a day or two of hacking I had the basic code working, ran through a few thousand files, and a malformed file blew up the sorter. That was OK, the sorter was intentionally naive and lacking in error handling; I wanted [...]]]></description>
			<content:encoded><![CDATA[<p>
I&#8217;m writing some Ruby scripts that sort and store lots of small files. After a day or two of hacking I had the basic code working, ran through a few thousand files, and a malformed file blew up the sorter. That was OK, the sorter was intentionally naive and lacking in error handling; I wanted it to hack it together and try out a few approaches before committing to serious development.
</p>

<p>
Now it&#8217;s time to treat it as real code, which means getting it under test. Tests are especially useful for ensuring tricky edge cases like malformed input don&#8217;t quietly break during other changes. When I started writing unit tests for the sorter I wanted fixtures similar to the <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL21hbnVhbHMucnVieW9ucmFpbHMuY29tL3JlYWQvY2hhcHRlci8yNg==">Rails fixtures</a> so I could write:
</p>

<pre>&nbsp;
<span style="color: #000066;">require</span> File.<span style="">dirname</span><span style="color: #66cc66;">&#40;</span>__FILE__<span style="color: #66cc66;">&#41;</span> + <span style="color: #ff0000;">'/../test_helper'</span>
<span style="color: #000066;">require</span> <span style="color: #ff0000;">'message'</span>
&nbsp;
class MessageTest &lt; Test::<span style="color: #006600;">Unit</span>::<span style="color: #006600;">TestCase</span>
  fixtures :message
&nbsp;
  def test_initialization
    f = Message.<span style="">new</span> message<span style="color: #66cc66;">&#40;</span>:good<span style="color: #66cc66;">&#41;</span>
    <span style="color: #808080; font-style: italic;"># assert the object was parsed correctly, etc.</span>
  <span style="color: #b1b100;">end</span>
end</pre>

<p>
The basic usage is <kbd>fixtures :type</kbd> to load the data and create the named function (in this case, <kbd>message</kbd>)  for fetching data. First, I wrote some <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3lhbWwub3JnL3N0YXJ0Lmh0bWw=">YAML</a> fixtures for my data and put them in <kbd>test/fixtures/message.yaml</kbd>. You can see the <kbd>:good</kbd> key in use here:
</p>

<pre>
good: |
  [the body of a good message here]
missing_header: |
  [more text]
bad_checksum: |
  [more text]
</pre>

<p>
Because I&#8217;m parsing textfiles my fixtures look pretty simple, but the <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5ydWJ5LWRvYy5vcmcvc3RkbGliL2xpYmRvYy95YW1sL3Jkb2MvaW5kZXguaHRtbA==">YAML library</a> for Ruby makes serialization of any very easy.
</p>

<p>
So here&#8217;s the code I put in <kbd>test/test_helper.rb</kbd> to set this up. I really like the <kbd>[list].flatten.each</kbd> idiom so the call from the unit test class can cleanly pass one or more types, eg: <kbd>fixtures :message</kbd> and <kbd>fixtures :message, :user</kbd>.
</p>

<pre>&nbsp;
class Test::<span style="color: #006600;">Unit</span>::<span style="color: #006600;">TestCase</span>
  <span style="color: #0000ff;">@@fixtures</span> = <span style="color: #66cc66;">&#123;</span><span style="color: #66cc66;">&#125;</span>
  def self.<span style="">fixtures</span> list
    <span style="color: #66cc66;">&#91;</span>list<span style="color: #66cc66;">&#93;</span>.<span style="">flatten</span>.<span style="">each</span> <span style="color: #b1b100;">do</span> |fixture|
      self.<span style="">class_eval</span> <span style="color: #b1b100;">do</span>
        <span style="color: #808080; font-style: italic;"># add a method name for this fixture type</span>
        define_method<span style="color: #66cc66;">&#40;</span>fixture<span style="color: #66cc66;">&#41;</span> <span style="color: #b1b100;">do</span> |item|
          <span style="color: #808080; font-style: italic;"># load and cache the YAML</span>
          <span style="color: #0000ff;">@@fixtures</span><span style="color: #66cc66;">&#91;</span>fixture<span style="color: #66cc66;">&#93;</span> ||= YAML::<span style="color: #006600;">load_file</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">"test/fixtures/#{fixture.to_s}.yaml"</span><span style="color: #66cc66;">&#41;</span>
          <span style="color: #0000ff;">@@fixtures</span><span style="color: #66cc66;">&#91;</span>fixture<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#91;</span>item.<span style="">to_s</span><span style="color: #66cc66;">&#93;</span>
        <span style="color: #b1b100;">end</span>
      <span style="color: #b1b100;">end</span>
    <span style="color: #b1b100;">end</span>
  <span style="color: #b1b100;">end</span>
end</pre>

<p>
(Note to Rails coders: I deliberately left out the pluralization, I like having the File class in <kbd>file.rb</kbd> with the fixtures in <kbd>text/fixtures/file.rb</kbd> and the database table named <kbd>file</kbd> and so on. I don&#8217;t mind Rails&#8217; convention of pluralizing to &#8220;files&#8221; in the latter two examples, but I&#8217;d rather have a single identifier.)
</p>

<p>
Last night at the <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3J1ZG9scGhoZXJpbmdzb2NpZXR5Lm9yZy9pbmRleC5waHA/dGl0bGU9TWFpbl9QYWdl">Rudolph Hering Society</a> meeting <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2Jsb2cuaWFuYmlja2luZy5vcmc=">Ian Bicking</a> and <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3Blb3BsZS5jcy51Y2hpY2Fnby5lZHUvfnZhcm1hYS8=">Atul Varma</a> explained mocking to me. I wrote a (very) little Ruby this morning to do mocking and I&#8217;ll post that in a day or two when I&#8217;m sure I didn&#8217;t do it too badly.
</p> <img src="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=250" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://push.cx/2007/fixtures-in-ruby-unit-tests/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

