Simplifying your tests with Shoulda Matchers
Created by Ana Schwendler, @anaschwendler
Shoulda Matchers is a Ruby testing gem, that provides RSpec- and Minitest-compatible one-liners that test common Rails functionality. These tests would otherwise be much longer, more complex, and error-prone.
COACH: Talk about testing and Behavior-Driven Development.
1. Add Shoulda Matchers gem
Open up your
Gemfile and add this line to the
:test group, above the end tag:
to install the gem.
COACH: Talk about googling terminal output.
2. Adjust your
In our case, we will be using RSpec to test our project, so we need to say to our
rails_helper.rb that we are using Shoulda Matchers:
Place above the last end tag (check the indentation):
COACH: Talk about why we are adjusting the gem inside
In your terminal run
It should show that our test is running ok.
It is pretty simple to test using Shoulda Matchers. For our first test we already stated that an Idea has many comments, in the Comments for Rails Girls App tutorial
To test if that is working properly, we can add the lines below to our
spec/lib/idea_spec.rb, above the first test that we’ve created:
This is an association test. COACH: Talk about association tests.
4. Test-Driven Development
COACH: Talk about TDD, and how we start adding features to our app by testing it first.
Another feature we can add to our app is to make ideas always named. How could we do that? Let’s get started saying ideas should always have a name.
Let’s begin by creating a test for it. We can do that by adding the following lines to our
add it below our association test.
After that, in your terminal run
It should gives us that we are not properly validating it (and we really are not). So to validate that, we need to add the following lines to our model, so we can validate the presence of name in our Idea.
add it below our has_many statement.
now, back in your terminal run
It should give the positive result.
5. Do it by yourself!
Can you continue this tutorial by doing a test to validate the presence of a description?
Can you imagine another tests to make?
- Handy cheatsheet for Ruby, Rails, console etc.
- Guide 1: Guide to install Rails
- Guide 2: Build Your First App
- Guide 3: Push Your App to GitHub
- Guide 4: Put your app online with…
- Guide 5: Allow Comments on Your App
- Guide 6: Add design using HTML & CSS
- Guide 7: Create thumbnails with Carrierwave
- Guide 8: Add Authentication (user accounts) with Devise
- Guide 9: Add Profile Pics with Gravatar
- Guide 10: Improve your design with HTML and CSS
- Guide 11: Continuous Deployment
- Guide 12: Build a voting app in Sinatra
- Guide 13: Build a diary app in Ruby on Rails
- Guide 14: Add a back-end to your app (admin pages)
- Guide 15: Go through additional explanations for the App