This is a guide for my Lighthouse Labs students who asked me to demonstrate unit-testing. Whenever a I initialize a new project, I have to relearn the whole setup process, so this serves as handy primer to both my students and myself.
Assuming Rails 5 is all set up and ready to go…
-T option skips creation of the default test files.
There are a bunch of gems I regularly use for testing:
Add them all these gems to the development/test group in your application’s
Install, of course:
Naturally, each of these new testing gems requires a bit of configuration to get working.
rspec is one of many great test suites. I like it the best, but that’s probably just because it’s the one I’m used to. It’s also great because a lot of people use it. So if you don’t know how to test something, chances are someone on StackOverflow does.
rspec-rails gem comes with a handy generator that does a bunch of the setup work for you:
This added a new
spec/ directory with a couple of helper files to your project. All your tests are stored in this directory. Run your
rspec tests like this:
We haven’t written any tests yet so you should see something like this:
shoulda-matchers make testing common Rails functionality much faster and easier. You can write identical tests in
rspec all by itself, but with
shoulda-matcher these common tests are reduced to one line.
To set this up, you paste the following to your
The tests you write with
shoulda-matcher get executed when you run your
capybara tests the totality of your application’s functionality by simulating how a real-world agent actually interacts with your app.
First, paste the following into your
Now, paste the following into your
This provides a nice way to spoof the models you create in your application. To use it, you need to add a couple of things to your
First, paste the following requirement:
Then, add the following to the
If everything is configured correctly, all the necessary test files will be created each time you generate some scaffolding. To see the options available, run
This will show you a list of installed generators, including all the
See what happens when you run
Take a peak in the
spec/ directory now. You’ll see a bunch of boilerplate test code waiting for you to fill in the blanks with meaningful tests.
Before you run the tests, though, you’ll need to migrate the database:
Now you can run the tests:
You’ll see a whole bunch of pending tests like this: