Skip to main content

Rails: Fat Tests Considered Unharmful

How many assertions should a test have? For instance, how many times should you use ".should" in an RSpec test? How many times should you use "Then" in a Cucumber test?

I have seen some developers work very hard to never have more than 1-2 assertions per test. They consider tests that are more than 3 lines long to be a code smell, and they tend to break up tests so that there is one assertion per test. I'd like to suggest that this conventional approach has some downsides that are too often overlooked.

First of all, what are the upsides of super skinny tests?

If you put 10 assertions each into their own test, then you can get very fine-grained results concerning which tests pass and which tests fail. That's useful. However, fine-grained results aren't all that crucial. I actually don't care all that much whether one test fails or ten tests fail. It doesn't really tell me how many bugs there are. Either way, it could be a single misspelling. Any number of tests failing is bad, and I don't regain confidence until all the tests are passing.

The next benefit of super skinny tests is that it helps prevent one assertion from affecting the outcome of another assertion. There's nothing more frustrating than tests that fail if you run them one way and pass if you run them another way. However, super skinny tests don't always address this problem. For instance, if you have data cached at the class level, that data will persist even between tests. Furthermore, a lot of tests are so simple you don't really need to worry very much about them affecting one another. For instance, if you check that a string contains "foo", that won't realistically have any affect on another assertion that checks whether it has "bar".

One more benefit of skinny tests is that they result in a comforting feeling. What's better 1000 tests or 1500 tests? The gut reaction is that 1500 tests is better, and I'll admit that I like lots of dots on the screen just as much as the next guy. However, if the 1500 tests only contain 1500 assertions whereas the 1000 tests contain 3000 assertions, it may be that the 1000 tests test more. I don't think there's any shame in adding a few more assertions to an existing test if you think that it adds real value to that test. Let's face it, testing isn't really about who can create the largest number of tests. It's about catching bugs that arise as the code is extended or refactored.

There's an old saying that says the best tests are the ones that get run. There's a hidden cost to super skinny tests that often gets overlooked. Consider the following hypothetical, functional RSpec test:
describe FilmsController do
before(:each) do
@film = Factory :film
get films_path
end

it "should have content" do
...
end

it "should set flash correctly" do
...
end

it "should have the right title" do
...
end

it "should set the right value for such and such assign" do
...
end

it "should set the right value for some other assign" do
...
end
end
What's wrong with this set of tests? Well, first of all, I prefer Cucumber integration tests over RSpec functional tests, but let's put that aside from a moment. There is a before filter that runs before each test. Hence, each test has to create a new film record and then regenerate the whole page. Generating the page probably results in a bunch of queries too. Let's assume 10 tests, 1 setup query per test, and 7 queries per page load. That's 80 queries for 10 assertions.

However, none of these assertions is all that complex. Furthermore, they're all simple enough that they are extremely unlikely to have side effects on one another. We could replace the before(:each) with a before(:all), but that turns out not to work out so well in practice. I suspect it's because each test runs in its own transaction.

Alternatively, we can collapse this into one test:
describe FilmsController do
it "should generate a proper index" do
@film = Factory :film
get films_path
test the content...
test the flash...
test the title...
test such and such assign...
test some other assign...
end
end
Not only does this remove a lot of boilerplate, it also cuts down the number of queries to 8. That means the tests run faster. When the tests run faster, they're more likely to be run as you develop. (I assume you already have integration testing that will run all the tests once you check the code in, but there's still value in running the tests as you develop.)

In conclusion, I think it's best not to go too overboard keeping your tests skinny. If two assertions require different setup, certainly put them in separate tests. However, once you have everything setup, if you can think of a few extra assertions that would add value to the test, don't be afraid to add them to the same test. I even like to occasionally add some assertions as I'm doing the setup just to make sure that the computer and I are on the same page (although I think it's best not to re-test things that have already been tested elsewhere). Certainly, I wouldn't recommend humongous tests that are 100s of lines long, but neither should every test be constrained to a single assertion.

Comments

Bob Van Zant said…
My current boss recently recommended this to me. I liked it and I have a feeling that you will as well. (Does this sound like spam or what?)

http://www.agitar.com/downloads/TheWayOfTestivus.pdf
Anthony said…
A suggestion: drop the word "should" from the it description. For example, instead of:

it "should generate a proper index"

use:

it "generates a proper index"

Also, I think I agree with your approach when you want to test the behavior, which is what you are testing in the example provided.
Stella said…
I completely agree. Controller tests are expensive and they take so long to run because of these shoulds for single assertions.

I combined all these shoulds and my boss and coworkers didn't like it even though it saved on their rake:test.

This is convention that should be discarded because it is overkill.
jjinux said…
From Shailen:

Hi JJ. You might want to look at this article:

http://blog.jayfields.com/2007/06/testing-one-assertion-per-test.html
jjinux said…
Hi, Shailen, I checked out that article, and I simply disagree (as I know you do as well).

Popular posts from this blog

Ubuntu 20.04 on a 2015 15" MacBook Pro

I decided to give Ubuntu 20.04 a try on my 2015 15" MacBook Pro. I didn't actually install it; I just live booted from a USB thumb drive which was enough to try out everything I wanted. In summary, it's not perfect, and issues with my camera would prevent me from switching, but given the right hardware, I think it's a really viable option. The first thing I wanted to try was what would happen if I plugged in a non-HiDPI screen given that my laptop has a HiDPI screen. Without sub-pixel scaling, whatever scale rate I picked for one screen would apply to the other. However, once I turned on sub-pixel scaling, I was able to pick different scale rates for the internal and external displays. That looked ok. I tried plugging in and unplugging multiple times, and it didn't crash. I doubt it'd work with my Thunderbolt display at work, but it worked fine for my HDMI displays at home. I even plugged it into my TV, and it stuck to the 100% scaling I picked for the othe

Drawing Sierpinski's Triangle in Minecraft Using Python

In his keynote at PyCon, Eben Upton, the Executive Director of the Rasberry Pi Foundation, mentioned that not only has Minecraft been ported to the Rasberry Pi, but you can even control it with Python . Since four of my kids are avid Minecraft fans, I figured this might be a good time to teach them to program using Python. So I started yesterday with the goal of programming something cool for Minecraft and then showing it off at the San Francisco Python Meetup in the evening. The first problem that I faced was that I didn't have a Rasberry Pi. You can't hack Minecraft by just installing the Minecraft client. Speaking of which, I didn't have the Minecraft client installed either ;) My kids always play it on their Nexus 7s. I found an open source Minecraft server called Bukkit that "provides the means to extend the popular Minecraft multiplayer server." Then I found a plugin called RaspberryJuice that implements a subset of the Minecraft Pi modding API for B

Creating Windows 10 Boot Media for a Lenovo Thinkpad T410 Using Only a Mac and a Linux Machine

TL;DR: Giovanni and I struggled trying to get Windows 10 installed on the Lenovo Thinkpad T410. We struggled a lot trying to create the installation media because we only had a Mac and a Linux machine to work with. Everytime we tried to boot the USB thumb drive, it just showed us a blinking cursor. At the end, we finally realized that Windows 10 wasn't supported on this laptop :-/ I've heard that it took Thomas Edison 100 tries to figure out the right material to use as a lightbulb filament. Well, I'm no Thomas Edison, but I thought it might be noteworthy to document our attempts at getting it to boot off a USB thumb drive: Download the ISO. Attempt 1: Use Etcher. Etcher says it doesn't work for Windows. Attempt 2: Use Boot Camp Assistant. It doesn't have that feature anymore. Attempt 3: Use Disk Utility on a Mac. Erase a USB thumb drive: Format: ExFAT Scheme: GUID Partition Map Mount the ISO. Copy everything from