Testing Newbie

November 25th, 2009

Last Spring I hosted a talk by Jon Yurek and Dan Croak of thoughtbot, inc entitled “Test Driven Development with Ruby on Rails”. And it was PACKED!!!

Many folks understand the importance of testing, the value-add, the business benefits of TDD, that’s why we were all there. We got a thorough overview of the numerous testing products. And there’s a LOT out there… or maybe it just seems that way. But once I was back at my desk facing my app, I still had trouble getting started.

Yeah, I’ve tried a few tutorials but they often only utilize the irb command line and don’t really explain how everything fits into a real live rails application.

Testing is just one of those things where you have to just dive in and go for it. That being said, let me share with you my endeavors using the Rails Guides.

1. Open your current ruby on rails project
Yeah, I said open your current project. If you don’t get started today, working every day, it’ll never happen right? But if you don’t have a current rails app and need some help getting started check out this Rails 2.0 step by step tutorial.

Okay now that we’re set up, we’re going to create a brand new model for the purposes of this testing tutorial:

>>ruby script/generate scaffold CoinChanger

By the way, don’t let anyone dissuade you from using scaffold. It’s much improved over older versions since 2.0 and comes packed with all kinds of goodies incredibly helpful to the newbie. You can always delete the files you don’t need later.

2. Write a Test
What already? Yeah.

>> cd test/unit

You should see the stub of a test already here:

require 'test_helper'
class CoinChangerTest < ActiveSupport::TestCase
# Replace this with your real tests.
test "the truth" do
assert true
end
end

I didn’t find this too terribly helpful in getting me started. Let’s instead replace the stub code with this:

require 'test_helper'
class CoinChangerTest < ActiveSupport::TestCase
def test_return_correct_change
#setup
#exercise
#verify
#teardown
end
end

So, require ‘test_helper’ specifies the default configuration to run our tests. It appears in every default test file. Doesn’t seem DRY to me. I betcha there’s a config file in the augmented testing frameworks where this would belong. But for now, we’ve leave it.

Next, you’ll notice that our CoinChangerTest class is extended by ActiveSupport::TestCase. Now, this is a little different than what you might find in those irb examples I mentioned before. Those examples extend Test::Unit::TestCase. Now that’s totally fine when you’re running a bunch of isolated files in a tutorial, but not when you’re working with a real rails app.

The class ActiveSupport::TestCase extends Test::Unit::TestCase and gives you all the testing goodness you need to run fixtures. We won’t be playing with data and fixtures in this tutorial (stayed tuned for future blog posts) but we’ll use the ActiveSupport class since we’re testing a full fledged rails application.

After that we see a pattern that will guide us through every test we write:

setup
exercise
verify (assert expectations)
teardown
So, here is an example of a unit test:

require 'test_helper'
class CoinChangerTest < ActiveSupport::TestCase
def test_return_correct_change_in_pennies
#setup
@changer = CoinChanger.new
#exercise
hash = @changer.change_me("$5.87")
#verify
assert_equal 2, hash[:pennies]
#teardown
# delete files, close network/database connections
end
end

In the example above, we setup an instance of my model class:

@changer = CoinChanger.new

Then we exercise the method which should return a hash:

hash = @changer.change_me("$5.87")

Then verify that the implementation works correctly by asserting expectations :

assert_equal 2, hash[:pennies]

Finally it’s time to clean up. There is nothing to teardown in this example. If the test were creating files or network/database connections, then we’d use the teardown method to close out:

assert_equal 2, hash[:pennies]

3. Run a Test
Go ahead. Try it out.

>> cd test
>> ruby unit/coin_changer_test.rb

Oh, dang! Get an error message? When you’re testing a rails application, you need to be sure that your database.yml is set up and pointing to a valid database. Those of you who just created a brand new rails app, you’ll need to edit your database.yml file. I’ll assume you can do this on your own, seriously, take a look at the Rails 2.0 step by step tutorial.

Let’s try again.

Loaded suite unit/coin_changer_test
Started
E
Finished in 0.219 seconds.
 1) Error:
test_return_correct_change(CoinChangerTest):
NoMethodError: undefined method `change_me' for #
unit/coin_changer_test.rb:11:in `test_return_correct_change'
1 tests, 0 assertions, 0 failures, 1 errors

Uh, oh. We forgot to create our change_me method in our CoinChanger model. Let’s do that now.

class CoinChanger
def change_me( dollar_string )
 #transform dollar string into change
return {}
 end
end

And rerun our test:

Loaded suite unit/coin_changer_test
Started
F
Finished in 0.344 seconds.
 1) Failure:
test_return_correct_change(CoinChangerTest) [u
expected but was
.
1 tests, 1 assertions, 1 failures, 0 errors

Well, now we’re getting somewhere! The test failed because it’s returning an empty hash. Let’s give our test what it wants:

def change_me( dollar_string )
#transform dollar string into change
return {:pennies => 587}
end

So, now if we run the test again… hopefully we see this:

Loaded suite unit/coin_changer_test
Started
Finished in 0.219 seconds.
1 tests, 1 assertions, 0 failures, 0 errors

This means the test passed and was successful. Yay!

Hopefully this is enough to get started. Stay tuned for more on testing!

Entry Filed under: Professional,Ruby on Rails

3 Comments Add your own

  • 1. wade  |  January 26th, 2010 at 5:51 pm

    Your code examples are riddled with html in the final rendering, which makes it kinda hard to read. Would be nice if it were fixed and leave the rendering to automation (or whatever is supposed to happen with your wordpress site).

  • 2. lianaleahy  |  February 2nd, 2010 at 12:10 pm

    I agree. It’s very annoying. Unfortunately, it is a plugin issue and I don’t have access to modify this instance of wordpress. *sigh*

  • 3. » Refactoring Geek &hellip  |  August 7th, 2010 at 12:13 pm

    [...] got a blog post that’ll walk you through the basics.  Chances are you’ve already seen the tutorials though and just need the confidence to get [...]

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Pages

RSS Tweets

RSS Berkman Gender & Tech

Links

Tags

Meta