High level Rails testing using Capybara and Minitest
When working on a new project or even a new feature, I’m often not too sure about the low level design of the code. In these cases, I’m starting to find higher-level tests very useful.
These tests help us define our objective in terms of how the user interacts with the application, and is not bothered with low level implementation details like names of the model or what methods handle the data.
Capybara is a library that lets us interact with the app as a user would see it, and perform actions like clicking on links or filling in and submitting forms. Using Capybara, we can simulate actions a user would perform on our site and test if it works as expected. These tests are called acceptance tests.
Setting up Capybara with Minitest for Rails
Here we will see how we can set up Capybara in a Rails project and use it along with Minitest. First, we will add the minitest-rails-capybara gem to the test group of our Gemfile.
We will need to include Capybara in our test helper. It should now look something like this:
Adding the first tests
Let’s add our first acceptance test. We will be testing the user registration page. There’s a handy generator to create the skeleton of the test.
This will create a new file
with an example test.
I prefer the spec syntax,
but if you wish to use
the default minitest assert syntax
you can omit the
As you can see, the generated file has an example test. Let’s edit this, and write a test for when the user enters valid input.
Now this test will be run
when we run all tests
Let’s add another test case
where the user enters invalid input -
in this case, the password is too short:
To test an application thoroughly, we need a mix of unit and acceptance tests. Acceptance tests will be much slower compared to our unit tests.
It’s a good idea to keep only a small number of acceptance tests that would cover your most important user stories. Avoid acceptance tests for edge cases, and instead let your unit tests cover those. This way, you will be able to keep your test suite fast, while also having confidence that your most important features have been thoroughly tested.