Basic Testing Introduction in Rails

Episode #100 by Teacher's Avatar David Kimura

Summary

Using the Rails 5.1.X defaults, we have a look at what is configured and explore the different types of tests; using the provided MiniTest and Capybara.
rails test 13:29

Resources

Summary

# Terminal
# Runs tests
rails test

# Runs system tests
rails test:system

# users_controller_test.rb
require 'test_helper'

class UsersControllerTest < ActionDispatch::IntegrationTest
  setup do
    @user = users(:one)
  end

  test "should get index" do
    get users_url
    assert_response :success
  end

  test "should get new" do
    get new_user_url
    assert_response :success
  end

  test "should create user" do
    assert_difference('User.count') do
      post users_url, params: { user: { email: @user.email, first_name: @user.first_name, last_name: @user.last_name } }
    end

    assert_redirected_to user_url(User.last)
  end

  test "should show user" do
    get user_url(@user)
    assert_response :success
  end

  test "should get edit" do
    get edit_user_url(@user)
    assert_response :success
  end

  test "should update user" do
    patch user_url(@user), params: { user: { email: @user.email, first_name: @user.first_name, last_name: @user.last_name } }
    assert_redirected_to user_url(@user)
  end

  test "should destroy user" do
    assert_difference('User.count', -1) do
      delete user_url(@user)
    end

    assert_redirected_to users_url
  end
end

# user_test.rb
require 'test_helper'

class UserTest < ActiveSupport::TestCase
  test "email validation should trigger" do
    assert_not User.new(first_name: 'First Name', last_name: 'Last Name').save
  end

  test "user should save" do
    assert User.new(first_name: 'First Name', last_name: 'Last Name', email: 'name@example.org').save
  end
end

# users_test.rb
require "application_system_test_case"

class UsersTest < ApplicationSystemTestCase
  test "visiting the index" do
    visit users_url
    assert_selector "h1", text: "User"
  end

  test "should create user" do
    visit new_user_url
    fill_in 'First name', with: 'first name'
    fill_in 'Last name', with: 'last name'
    fill_in 'Email', with: 'user1@example.com'
    click_button 'Create User'

    visit users_url
    within 'table' do
      assert_selector 'tr td', text: 'first name'
      assert_selector 'tr td', text: 'last name'
      assert_selector 'tr td', text: 'user1@example.com'
    end
  end
end

# user.rb
class User < ApplicationRecord
  validates :email, presence: true
end

# users.yml
one:
  first_name: MyString
  last_name: MyString
  email: MyString

two:
  first_name: MyString
  last_name: MyString
  email: MyString