<?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>confabulus &#187; testing</title>
	<atom:link href="http://blog.confabulus.com/category/rails/testing/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.confabulus.com</link>
	<description>rails, coding, and the goings on at confabulus</description>
	<lastBuildDate>Fri, 19 Feb 2010 22:08:06 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Making your Plugin or Gem configurable</title>
		<link>http://blog.confabulus.com/2008/12/30/making-your-plugin-or-gem-configurable/</link>
		<comments>http://blog.confabulus.com/2008/12/30/making-your-plugin-or-gem-configurable/#comments</comments>
		<pubDate>Wed, 31 Dec 2008 02:41:32 +0000</pubDate>
		<dc:creator>gaffo</dc:creator>
				<category><![CDATA[configuration]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[plugins]]></category>
		<category><![CDATA[rspec]]></category>
		<category><![CDATA[test::unit]]></category>

		<guid isPermaLink="false">http://blog.confabulus.com/?p=105</guid>
		<description><![CDATA[Recently I added a configuration mechanism to Webrat. It was surprisingly easy, and mainly copied from rails core. I would suggest adding somthing like this to any plugin that has more than a few features or ones that users have asked to have turned off.
First off you&#8217;re going to have to create the actual configuration [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I added a configuration mechanism to Webrat. It was surprisingly easy, and mainly copied from rails core. I would suggest adding somthing like this to any plugin that has more than a few features or ones that users have asked to have turned off.</p>
<p>First off you&#8217;re going to have to create the actual configuration object. There are a few good ways to do this. One is to use a <a href="http://toolmantim.com/article/2007/5/18/consolidating_your_apps_constants">config module</a>, another is to create a configuration object that is accessible via a singleton method.</p>
<p>I&#8217;m going to go with the second one, a configuration object.</p>
<p>Toss this one in lib/configuration.rb (A simplification of <a href="http://github.com/brynary/webrat/tree/2c51d908301e23a8594eda49f0d64ce197b3e842/lib/webrat/core/configuration.rb">Code</a> | <a href="http://rdocul.us/repos/webrat/master/classes/Webrat/Configuration.html">RDoc</a>) </p>
<pre class="brush: ruby">
module Plugin

  # Configures Plugin.
  def self.configure(configuration = Plugin::Configuration.new)
    yield configuration if block_given?
    @@configuration = configuration
  end

  def self.configuration # :nodoc:
    @@configuration ||= Plugin::Configuration.new
  end

  # Plugin can be configured using the Plugin.configure method. For example:
  #
  #   Plugin.configure do |config|
  #     config.show_whiny_errors = false
  #   end
  class Configuration

    # Should whiny error messages be shown?
    attr_writer :show_whiny_errors

    def initialize # :nodoc:
      # set your defaults in here
      self.show_whiny_errors = true
      # put as much as you want in here
    end

    # some syntactic sugar for you, the coder
    def show_whiny_errors? #:nodoc:
      @show_whiny_erorrs ? true : false
    end

  end

end
</pre>
<p>Okay, now we need to test the config object itself. This is why it&#8217;s nice to make an object just to house the config, it&#8217;s easy to test. What do we test? Well defaults and accessors for two!</p>
<p>(The following lifted from <a href="http://github.com/brynary/webrat/tree/2c51d908301e23a8594eda49f0d64ce197b3e842/spec/webrat/core/configuration_spec.rb">Code</a>) (sorry this is in rspec, it&#8217;s not hard to do in test::unit)</p>
<pre class="brush: ruby">
require File.expand_path(File.dirname(__FILE__) + &#039;/../../spec_helper&#039;)

describe Plugin::Configuration do
  # define matchers for testing
  predicate_matchers[:show_whiny_errors] = :show_whiny_errors?

  it &#039;should show whiny errors by default&#039; do
    config = Plugin::Configuration.new
    config.should show_whiny_errors?
  end

  it &#039;should be configurable with a block&#039; do
    Plugin.configure do |config|
      config.show_whiny_errors = false
    end

    config = Plugin.configuration
    config.should_not show_whiny_errors?
  end

end
</pre>
<p>Now we need to do some stuff to make it nicer for our other users to test. Put the following in your test_helper or spec helper. It will allow you to clear your config after each test. Nice to have to to avoid messy test issues.</p>
<p>(The following lifted from <a href="http://github.com/brynary/webrat/tree/2c51d908301e23a8594eda49f0d64ce197b3e842/spec/spec_helper.rb">Code</a>)</p>
<pre class="brush: ruby">
module Plugin
  @@previous_config = nil

  def self.cache_config_for_test
    @@previous_config = Plugin.configuration.clone
  end

  def self.reset_for_test
    @@configuration = @@previous_config if @@previous_config
  end
end

# configure your test runner / spec runner to always clear the config
Spec::Runner.configure do |config|

  config.before :each do
    Plugin.cache_config_for_test
  end

  config.after :each do
    Plugin.reset_for_test
  end
end
</pre>
<p>This last bit is somewhat hard to do in test::unit as it is harder to hook into the setup (you only get one in the call chain). I&#8217;m willing to take some help on cleaning this one up for test::unit. Currently I have just been putting it in the setup / teardown for each test file.</p>
<p>Finally you need to make use of this in tests, fortunately that is quite easy. Just:</p>
<pre class="brush: ruby">
describe SomeObject do
    it &#039;it shouldn&#039;t do it when whiny nils are off&#039; do
      Plugin.configure do |config|
        config.show_whiny_errors = false
      end
      object.should_not_receive(:log)

      object.do_somthing_that_usually_complains
    end
end
</pre>
<p>Finally, anywhere in your plugin that you think somthing is whiny, just check the config before using it like this:</p>
<pre class="brush: ruby">
log(&amp;quot;you should really fix this&amp;quot;) if Plugin.configuration.show_whiny_errors?
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.confabulus.com/2008/12/30/making-your-plugin-or-gem-configurable/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>testing named scopes</title>
		<link>http://blog.confabulus.com/2008/11/24/testing-named-scopes/</link>
		<comments>http://blog.confabulus.com/2008/11/24/testing-named-scopes/#comments</comments>
		<pubDate>Tue, 25 Nov 2008 02:33:58 +0000</pubDate>
		<dc:creator>gaffo</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://blog.confabulus.com/?p=80</guid>
		<description><![CDATA[Named scopes are a nice feature that came out in rails 2.1, however, testing them is not very obvious.
Say we have a named scope in our member object which looks like this:

class Member &#60; ActiveRecord::Base
  named_scope :active, {:conditions =&#62; {:status =&#62; Member::STATUS_ACTIVE}}
end

There are 2 things we need to do to test them. 
First would [...]]]></description>
			<content:encoded><![CDATA[<p>Named scopes are a nice feature that came out in rails 2.1, however, testing them is not very obvious.</p>
<p>Say we have a named scope in our member object which looks like this:</p>
<pre class="brush: ruby">
class Member &lt; ActiveRecord::Base
  named_scope :active, {:conditions =&gt; {:status =&gt; Member::STATUS_ACTIVE}}
end
</pre>
<p>There are 2 things we need to do to test them. </p>
<p>First would be to make sure that the conditions are the same as we think they are. This one is open for debate a bit as it is somewhat tying the implementation directly to the test.</p>
<p>Second, we actually have to USE the scope. Just calling Member.active does not actually use the scope. This is because named scopes can be cascaded. If I had recent scope on a member that only showed me those that signed up recently, I could actually do Member.active.recent, and it would not execute against database, it would just nest the conditions.</p>
<p>So how do I use the scope? Use any collection method on them. I like size, but I&#8217;m completely open to suggestions. So below is how I am testing named scopes.</p>
<pre class="brush: ruby">
class MemberTest &lt; ActiveRecord::TestCase
  context &#039;named scope active&#039; do
    setup do
      @scoped_find = Member.active
    end

    should &quot;have condition active&quot; do
      expected_conditions  = {:conditions =&gt; [&quot;member.status == #{Member::STATUS_ACTIVE}&quot;]}
      assert_equal expected_conditions, @scoped_find.proxy_options
    end

    should &quot;have results&quot; do
      assert_not_nil(scoped.active.size)
    end
  end
end
</pre>
<p>The first test does part 1, the 2nd, part 2.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.confabulus.com/2008/11/24/testing-named-scopes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>testing protected and private methods in ruby</title>
		<link>http://blog.confabulus.com/2008/10/26/testing-protected-and-private-methods-in-ruby/</link>
		<comments>http://blog.confabulus.com/2008/10/26/testing-protected-and-private-methods-in-ruby/#comments</comments>
		<pubDate>Sun, 26 Oct 2008 19:39:14 +0000</pubDate>
		<dc:creator>gaffo</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[def]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://blog.confabulus.com/?p=31</guid>
		<description><![CDATA[When I was looking for how to test protected an private methods in ruby on the net, I found many sites arguing whether you should, and several methods for doing so. I am of the opinion that if your method contains any logic at all, it should have a test. Some examples of what I [...]]]></description>
			<content:encoded><![CDATA[<p>When I was looking for how to test protected an private methods in ruby on the net, I found many sites arguing whether you should, and several methods for doing so. I am of the opinion that if your method contains any logic at all, it should have a test. Some examples of what I consider logic:</p>
<p><strong>Object:</strong></p>
<pre class="brush: ruby">
class User
  validates_presence_of :first_name, :last_name, :company_id
  belongs_to :company
  def full_name
    &quot;#{last_name}, #{first_name}&quot;
  end
  def company_name
    company.name
  end
end
</pre>
<p><strong>Test:</strong></p>
<pre class="brush: ruby">
class UserTest &lt; Test::Unit
  def test_full_name
    assert_equal(&quot;Gaffney, Mike&quot;, User.new(:first_name =&gt; &quot;Mike&quot;, :last_name =&gt; &quot;Gaffney&quot;))
  end
  def test_company_name
    company = Company.new(:name =&gt; &quot;CompanyName&quot;)
    user = User.new(:company =&gt; company)
    assert_equal(&quot;CompanyName&quot;, user.company_name)
  end
end
</pre>
<p>This may seem like overkill but when many people are looking at the code it greatly helps communicate intention to others.</p>
<p><strong>Testing:</strong></p>
<p>I also found several methods to test protected and private methods in ruby, so I will cover the pluses and minuses the ones I know of.</p>
<p>Lets say we have a User class and an unassociated comments class. Comments are only attributed to a poster&#8217;s full name. There is no direct ID link between comments and users.</p>
<pre class="brush: ruby">
class User
  validates_presence_of :first_name, :last_name
  def find_comments
    Comments.find(:all, :conditions =&gt; {:poster =&gt; full_name})
  end
  protected
  def full_name
    &quot;#{last_name}, #{first_name}&quot;
  end
end
</pre>
<p>Here are the approaches I&#8217;m going to use to test this:</p>
<ul>
<li>Using a Mock to open access restrictions</li>
<li>Make single (protected/private) methods public on the tested class.</li>
<li>Make all (protected/private) methods public on the tested class.</li>
<li>Hybrid Mock Approach</li>
<li>Using instance_eval and send</li>
<li>send</li>
</ul>
<p><strong>Using Mocks:</strong><br />
Mocks should be pretty familiar to most developers. Basically you create a class or subclass that the test will use. In our case we are simply opening the access restrictions with a subclass. Our test class looks like this:</p>
<pre class="brush: ruby">
class MockUser &lt; User
  def full_name
    super
  end
end
class UserTest &lt; Test::Unit
  def test_full_name
    user = User.new(:first_name =&gt; &quot;Mike&quot;, :last_name =&gt; &quot;Gaffney&quot;)
    assert_equal(&quot;Gaffney, Mike&quot; user.full_name)
  end
end
</pre>
<p>Plusses:</p>
<ul>
<li>Simple and familiar to most developers from many languages</li>
</ul>
<p>Minuses:</p>
<ul>
<li>Can&#8217;t test private methods (subclass doesn&#8217;t have access).</li>
<li>With complicated classes you end up with quite a few mocks for all of the different cases. Managing the mocks becomes tedious.</li>
</ul>
<p><strong>Make single methods public:</strong><br />
Next we will make use of the runtime nature of ruby to change a function from protected to public. This also works for private methods:</p>
<pre class="brush: ruby">
class UserTest &lt; Test::Unit
  def test_full_name
    User.send(:public, :first_name)
    user = User.new(:first_name =&gt; &quot;Mike&quot;, :last_name =&gt; &quot;Gaffney&quot;)
    assert_equal(&quot;Gaffney, Mike&quot; user.full_name)
  end
end
</pre>
<p>or</p>
<pre class="brush: ruby">
class User
    public :first_name
end
class UserTest &lt; Test::Unit
  def test_full_name
    user = User.new(:first_name =&gt; &quot;Mike&quot;, :last_name =&gt; &quot;Gaffney&quot;)
    assert_equal(&quot;Gaffney, Mike&quot; user.full_name)
  end
end
</pre>
<p>Plusses:</p>
<ul>
<li>Lets us directly access the private or protected function.</li>
</ul>
<p>Minuses:</p>
<ul>
<li>This pollutes the default namespace for all of the other tests. Remember that tests can (and should be able to) run in random order. Take for example:
<ol>
<li>Full Name is a public function that some other objects use.</li>
<li>We make this function into a protected one and use this method to make it public for testing.</li>
<li>If this new test runs before the tests for the objects using the old public full_name, full_name will still be public even though it is actually protected.</li>
<li>The other tests do not fail but the code will fail during runtime.</li>
</ol>
</ul>
<p><strong>Make all methods public:</strong><br />
To save us some time on a big class, we can make all private and protected methods public:</p>
<pre class="brush: ruby">
class User
  public *protected_methods.collect(&amp;amp;amp;amp;:to_sym)
  public *private_methods.collect(&amp;amp;amp;amp;:to_sym)
end
class UserTest
  def test_full_name
    user = User.new(:first_name =&gt; &quot;Mike&quot;, :last_name =&gt; &quot;Gaffney&quot;)
    assert_equal(&quot;Gaffney, Mike&quot; user.full_name)
  end
end
</pre>
<p>or </p>
<pre class="brush: ruby">
class UserTest &lt; Test::Unit
  def test_full_name
    User.send(:public, *MyClass.protected_instance_methods)
    User.send(:public, *MyClass.private_instance_methods)
    user = User.new(:first_name =&gt; &quot;Mike&quot;, :last_name =&gt; &quot;Gaffney&quot;)
    assert_equal(&quot;Gaffney, Mike&quot; user.full_name)
  end
end
</pre>
<p>This has the same issues as above but can be done one to make large classes easy to test, especially using the first method.</p>
<p><strong>Hybrid Approach:</strong><br />
This works like the mock example and the previous example combined:</p>
<pre class="brush: ruby">
class AllAccessUser
  public *protected_methods.collect(&amp;amp;amp;amp:to_sym)
end
class UserTest &lt; Test::Unit
  def test_full_name
    user = AllAccessUser.new(:first_name =&gt; &quot;Mike&quot;, :last_name =&gt; &quot;Gaffney&quot;)
    assert_equal(&quot;Gaffney, Mike&quot; user.full_name)
  end
end
</pre>
<p>This is easy like the previous but does not pollute the namespace. However it cannot be used for private methods.</p>
<p><strong>Using send</strong><br />
Now we will use the built in reflection method to call the protected/private method on the class. This makes use of the fact that protected and private in ruby aren&#8217;t really like protected and private in other languages.</p>
<pre class="brush: ruby">
class UserTest &lt; Test::Unit
  def test_full_name
    user = User.new(:first_name =&gt; &quot;Mike&quot;, :last_name =&gt; &quot;Gaffney&quot;)
    assert_equal(&quot;Gaffney, Mike&quot; user.send(:full_name))
  end
end
</pre>
<p>Plusses:</p>
<ul>
<li>Doesn&#8217;t pollute the namespace.</li>
<li>All code is right in the test.</li>
<li>Works for protected and private.</li>
</ul>
<p>Minuses:</p>
<ul>
<li>Some people don&#8217;t like using send </li>
</ul>
<p><strong>Summary:</strong><br />
Testing protected and private methods should be done, and ruby makes it much easier than some other languages. My preferred technique is the final one of using send. It is slightly less readable but keeps everything contained in one location.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.confabulus.com/2008/10/26/testing-protected-and-private-methods-in-ruby/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>rcov and rails</title>
		<link>http://blog.confabulus.com/2008/06/11/rcov-and-rails/</link>
		<comments>http://blog.confabulus.com/2008/06/11/rcov-and-rails/#comments</comments>
		<pubDate>Thu, 12 Jun 2008 02:05:31 +0000</pubDate>
		<dc:creator>gaffo</dc:creator>
				<category><![CDATA[rails]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[rcov]]></category>

		<guid isPermaLink="false">http://blog.confabulus.com/?p=9</guid>
		<description><![CDATA[rcov and Rails
I had the good fortune of attending Rails Conf recently on behalf of the consulting company I work for, Asynchrony Solutions. One of the topics at the great Refactotem tutorial (hosted by the guys from Relevance) was rcov, a code coverage tool for Ruby. One of the things I missed in, or was [...]]]></description>
			<content:encoded><![CDATA[<p>rcov and Rails<br />
I had the good fortune of attending Rails Conf recently on behalf of the consulting company I work for, <a href="http://www.asolutions.com">Asynchrony Solutions</a>. One of the topics at the great Refactotem tutorial (hosted by the guys from <a href="http://thinkrelevance.com/">Relevance</a>) was <a href="http://eigenclass.org/hiki.rb?rcov">rcov</a>, a code coverage tool for Ruby. One of the things I missed in, or was neglected from, the talk was how to actually run coverage tasks against Rails. So I thought I would share the code to make the test:coverage task that I found with some digging.</p>
<p>Add the following to the Rakefile in the root of your rails app:</p>
<pre class="brush: ruby">
require &#039;rcov/rcovtask&#039;

namespace :test do
namespace :coverage do
desc &quot;Delete aggregate coverage data.&quot;
task(:clean) { rm_f &quot;coverage.data&quot; }
end
desc &#039;Aggregate code coverage for unit, functional and integration tests&#039;
  task :coverage =&gt; &quot;test:coverage:clean&quot;
    %w[unit functional integration].each do |target|
    namespace :coverage do
      Rcov::RcovTask.new(target) do |t|
      t.libs &lt;&lt; &quot;test&quot;
      t.test_files = FileList[&quot;test/#{target}/*_test.rb&quot;]
      t.output_dir = &quot;test/coverage/#{target}&quot;
      t.verbose = true
      t.rcov_opts &lt;&lt; &#039;--rails --aggregate coverage.data&#039;
    end
  end
  task :coverage =&gt; &quot;test:coverage:#{target}&quot;
  end
end
</pre>
<p>You can then run rcov on  your rails app by running:<br />
<code><br />
rake test:coverage</code></p>
<p>After this completes, it will output index.html files in RAILS_ROOT/tests/coverage/[units, functional, integration]. There is no overall index file, as, if you read the rake task, it is running rcov separately for each of [units, functional, integration].</p>
<p>Rcov has a few things to work out like showing untested code in modules sometimes, but otherwise it gives you a good idea of sections and branches of your code that are not tested. It’s very easy to set up so why not give it a try. But remember, metrics can only help point out problem spots in your code, they are not a replacement for good coding techniques.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.confabulus.com/2008/06/11/rcov-and-rails/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
