Thomas McGoey-Smith

Utilizing one assert per test

One of the problems I’ve been having is trying to keep just to a single test.

For example, I have a Shop model that I wanted to make sure some defaults are set properly.

Originally, I thought it was best to just test if the defaults were all set. This to me sorta made sense.

test "newly created shop should have initial defaults set properly" do
  s = Shop.create(shopify_domain: 'testshop1.myshopify.com', shopify_token: 'somethingsupersecure')
  assert s.valid?
  assert s.install_required # my defaults I'm trying to test for
  assert s.setup_required
end

But I came across this post from 2007 by Jay Fields. That outlined an argument for just having a single assert per test.

The biggest argument against multiple asserts is the fact that you find out all your failing tests right away. Instead you might need to fix the first bug in order to uncover the next.

So here’s what my new tests look like:

test "newly created shop should be valid" do
  s = Shop.create(shopify_domain: 'testshop1.myshopify.com', shopify_token: 'somethingsupersecure')
  assert s.valid?
end

test "newly created shop should have install_required true" do
  s = Shop.create(shopify_domain: 'testshop1.myshopify.com', shopify_token: 'somethingsupersecure')
  assert s.install_required
end

test "newly created shop should have setup_required true" do
  s = Shop.create(shopify_domain: 'testshop1.myshopify.com', shopify_token: 'somethingsupersecure')
  assert s.setup_required
end

@tamcgoey on Feb 09, 2016

Enjoyed the article? Subscribe to my newsletter for more.

© Thomas McGoey-Smith (2014-2018). RSS.