Adding Unit Test to Rails App
Tests were not a huge part of my learning when I was going through the Flatiron bootcamp. We focused much more on BDD or behavior driven development.
However, in the real world it seems that tests are much more of a mainstay. I recently began adding tests to one of my projects, a blog application. This blog will detail the very basic steps I took to start running model tests in my Ruby on Rails application.
First, in your Rails directory, go into the folder called test.
Within that directory find a folder called models.
Create a file in that folder named modelname_test.rb.
In this file, what I did was first require the rails test helper at the top of the page, then define my CategoryTest class inheriting from ActiveSupport::TestCase.
require 'test_helper'class CategoryTest < ActiveSupport::TestCaseend
Within this class you can define your tests.
One thing that will make your life easier is to define a testable model instance variable at the beginning of the class so you can refer to it for all of your tests.
require 'test_helper'class CategoryTest < ActiveSupport::TestCasedef setup@category = Category.new(name: "Politics")endend
After this you can start writing your tests.
Here’s an example test :
require 'test_helper'class CategoryTest < ActiveSupport::TestCasedef setup@category = Category.new(name: "Politics")endtest "category should be valid" doassert @category.valid?endend
By running Rails test in your terminal, this will run tests to validate that the @category instance variable would be valid to save to the database (determined by the validations you set within your Category model).