Let's set up a few things to improve the overall testing mechanics of this app.
One thing at a time:
Adding pry-rails outside of the :development, :test groups so that
rails console or
rails c can ben run in any environment, with the benefit of pry.
factory_bot_rails will allow rapid creation of records within the scope of our tests.
faker will allow us to populate those records with realistic fake data.
simplecov is a code coverage reporter. This will let us know if our tests are doing their job.
brakeman is a tool for auditing our entire application for security issues. I haven't used this before but it seems like a very good idea.
Finally, guard-rspec, which includes guard is a nifty little program that will watch our code for changes and quickly run and re-run the related tests and report the test status in OS-specific notifications.
I'm going to go kind of in reverse, from bottom to top.
bundle exec guard init rspec
This will generate a Guardfile for us. But it doesn't include any expressions for rspec request specs, which I will make heavy use of. I amend this section of the Guardfile like so:
Don't check coverage reports into git. Add this to .gitignore:
At the very top of the spec_helper.rb file add:
Now whenever your (rspec) test are run (e.g. by guard-rspec), files inside of
coverage/ will be updated. Open
coverage/index.html in a browser, and keep it refreshed to see the latest test coverage report.
In the spec/rails_helper.rb file there is a little section below
require 'rspec/rails to add additional requires:
Create a spec/support folder if it doesn't already exist, and also create a spec/factories folder, and make this file:
This ensures that factories are available in all of the spec files.
Speaking of factories, I'm going to make one for my Food model:
Yes, faker comes with a Food module!
Now I can refactor the 2nd test in my foods_request_spec as such (the first test doesn't use any data):
Notice the use of
create_list(:food, 3). That auto-magically generates 3 Food records. I have to be a bit more clever in verifying the names and ids because now they are random instead of hard-coded. But on the plus side I'm no longer relying on hard-coded data in my test. This will bear fruit as things increase in complexity.
One More Thing
By default the included spec/spec_helper.rb file has a block of options that are commented out, from
=end. I like to delete the lines of code with
=end on them and so enable all of those optional configurations. This includes enabling the
:focus symbol to run just one test, and running the tests in a random order.