<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="/stylesheets/rss.css"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">
  <channel>
    <title>a timocracy of one: Calling (invoking) rails rake tasks from within ruby, for testing, try 2</title>
    <link>http://www.timocracy.com/articles/2008/02/21/calling-invoking-rails-rake-tasks-from-within-ruby-for-testing-try-2</link>
    <language>en-us</language>
    <ttl>40</ttl>
    <description>Tim Connor's Blog</description>
    <item>
      <title>Calling (invoking) rails rake tasks from within ruby, for testing, try 2</title>
      <description>&lt;p&gt;Yesterday I wrote a post on &lt;a href="http://www.timocracy.com/articles/2008/02/20/capturing-a-system-call-in-ruby-with-backticks-while-setting-an-environment-variable"&gt;capturing the output of rake from a ruby call using backticks&lt;/a&gt;, because I wanted to do so in a test.  Well, I had Date.today stubbed out, but got lazy and used yesterday&amp;#8217;s date, so of course when I come in today the test fails.  In the light of a new day my problem was obvious. If you call rake from a sub-shell, say via ``, of course your mocking will not exist in that process. So today, I had Another Wonderful Opportunity for Learning (there are acronyms for this that use a different word than wonderful): a chance to do it right.&lt;/p&gt;


It took a little digging to figure out how to get this to work right with the built-in rails tasks, so here you go:
&lt;pre&gt;&lt;code&gt;
require 'rake'
require 'rake/rdoctask'
require 'rake/testtask'
require 'tasks/rails'

def capture_stdout
  s = StringIO.new
  oldstdout = $stdout
  $stdout = s
  yield
  s.string
ensure
  $stdout = oldstdout
end

Rake.application.rake_require '../../lib/tasks/metric_fetcher'
results = capture_stdout {Rake.application['metric_fetcher'].invoke}
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;I liberated capture_stdout from the rake tests themselves.  In retrospect, I should have just looked there first.  As &lt;span class="caps"&gt;TDD&lt;/span&gt; and especially &lt;span class="caps"&gt;BDD&lt;/span&gt; get even more widespread the tests are often the easiest place to look for good examples of usage.&lt;/p&gt;</description>
      <pubDate>Thu, 21 Feb 2008 13:48:00 -0800</pubDate>
      <guid isPermaLink="false">urn:uuid:5c83530d-67d8-4da7-9f00-79d68dffb89d</guid>
      <author>Tim Connor</author>
      <link>http://www.timocracy.com/articles/2008/02/21/calling-invoking-rails-rake-tasks-from-within-ruby-for-testing-try-2</link>
      <category>Rails</category>
      <category>rake</category>
      <category>ruby</category>
      <category>testing</category>
    </item>
  </channel>
</rss>
