A Peek into Daily Development at FiveRuns

I wrote a post today for the FiveRuns corporate blog entitled ‘Beyond Continuous Integration: Continuous Information‘.  It’s a quick look at some of the tools and practices we use daily on the development team.

Don’t assert when you mean to assert_equal

Pop quiz: which of these test assertions will pass?

    assert true
    assert true, true
    assert true, false
    assert true, 'false'
    assert 'true', false
    assert 'true', 'true'
    assert 'true', 'false'

You might be surprised to learn that every single one of these assertions pass successfully. From the documentation, you can see that assert() takes 2 arguments: a boolean and an optional message. In each of the above cases, you’re passing a true value as the first argument and then an (unintended) optional message.

What you probably meant to do is use assert_equal(). This method takes 3 arguments: 2 boolean values and an optional message. This is the one you need when you intend to compare 2 values against each other.

Posted in ruby, test. 2 Comments »

Use dispatch() in your Merb 0.3.7 controller tests

It took me a little while to determine how to best test my Merb controller logic. Hopefully, this post will save you the time. The following is an excerpt from an example test/spec test of mine. It’s a tiny bit verbose for the sake of clarity.

require File.dirname(__FILE__) + '/test_helper'

context "Posts Controller" do

  setup do
    Post.delete_all
  end

  specify "should list all posts" do
    create_valid_posts 4

    headers = {}
    params = {:action => :index}
    request = Merb::Test::FakeRequest.with("/posts", "GET")
    response = StringIO.new

    controller = Posts.build(request, headers, params, response)
    controller.dispatch(:index)

    posts = controller.instance_variable_get("@posts")

    assert 4, posts.size
  end

  #######
  private
  #######

  def create_valid_posts(num_posts=1)
    num_posts.times do |num|
      Post.create(:title => "Blog Post #{num}")
    end
  end

end

There are a couple of key things to note here:

  1. Calling Controller#dispatch() will run the action with its before- and after-filters. That’s what you want. Calling Controller#action_name() will just run the action, disregarding any filter chain you have in place.
  2. Controller#instance_variable_get() gives you access to any instance variables you set in the controller. Use this to verify that you have set up the variables you expect.
Posted in merb, ruby, test. 2 Comments »
Follow

Get every new post delivered to your Inbox.