June 30, 2006

Posted by John

Tagged testing

Older: Curious Where Rails is Heading?

Newer: Keynote Videos

assert_difference for easier tests

I have finally had the time to really get into testing and wow is it cool. You know that feeling you get every now and then (speaking to those who don’t test)? That feeling of, “what if my code is not working?” That feeling of what did I screw up when I made that tiny change. Well, testing removes that feeling and replaces it with a smile. Anytime I start to feel that doubt creep in, I run another test and click my heels. At any rate, I’ll get back on track as to why I’m writing this post.

I know assert_difference is probably old news to most but tonight it blew me away. So here is one of my old nasty tests …

def test_should_destroy_subscriptions
  f = feeds(:addictedtonew)
  subs_count = Subscriptions.find(:all).size
  deleted_subs = f.subscriptions.size
  assert Feed.destroy(f.id)
  assert_equal subs_count - deleted_subs, Subscriptions.find(:all).size
end

Basically, I get a feed, get the total number of subscriptions, delete the feed, which in turn deletes all the subscriptions to the feed, and finally check if the number of subscriptions minus the number deleted matches the number in the table. Sure it works, but it was starting to get annoying real quick having each of my tests store the total value and then test that old value plus or minus the change against the current value.

I started looking in some sample apps I had downloaded from Railsday and noticed assert_difference. Duh…I knew immediately this was exactly what I wanted. I rewrote the test to look like this …

def test_should_destroy_subscriptions
  f = feeds(:addictedtonew)
  assert_difference Subscription, :count, -f.subscriptions.size do
    assert Feed.destroy(f.id)
  end
end

This test does the exact same thing as the previous, but is more readable and less lines of code. Basically, it asserts that there is a difference of the number of f’s subscriptions in the count of all the subscriptions before and after the yielded block. Here’s to happier testing for those who haven’t discovered this jewel yet like me!

1 Comment

  1. Minal Jain Minal Jain

    Jan 13, 2010

    Goodone this will solve my query about how and when assert_difference is used..
    Thanks a lot !!!!!!!!!!

    Minal :):)

Thoughts? Do Tell...


textile enabled, preview above, please be nice
use <pre><code class="ruby"></code></pre> for code blocks

About

Authored by John Nunemaker (Noo-neh-maker), a programmer who has fallen deeply in love with Ruby. Learn More.

Projects

Flipper
Release your software more often with fewer problems.
Flip your features.