Quote Rails Tutorial
The word is to make sure that the feature is implemented correctly. It's also a safety net when it comes to writing tests, and it's itself an "executable document" of your application's source code. With all the tests in place, you don't have to spend extra time chasing bugs, and if done right, it's definitely faster than without tests.
The test file is created when rails generate controller is executed in the terminal.
Terminal
#Example
$ rails generate controller StaticPages home help
↓
test/controllers/static_pages_controller_test.rb
require 'test_helper'
class StaticPagesControllerTest < ActionDispatch::IntegrationTest
test "should get home"do ← home page test
get static_pages_home_url ← Send GET request to home action
assert_response :success ← The response to the request should be [Success]
end
test "should get help" do
get static_pages_help_url
assert_response :success
end
end
↓
Terminal
$ rails db:migrate #Required by some systems
$ rails test
2 tests, 2 assertions, 0 failures, 0 errors, 0 skips
The code is implemented without any problem because of 0 errors.
Assuming you added the about page, try adding the code.
test/controllers/static_pages_controller_test.rb
require 'test_helper'
class StaticPagesControllerTest < ActionDispatch::IntegrationTest
test "should get home" do
get static_pages_home_url
assert_response :success
end
test "should get help" do
get static_pages_help_url
assert_response :success
end
test "should get about" do
get static_pages_about_url
assert_response :success
end
end
Test run
Terminal
$ rails test
NameError: undefined local variable or method `static_pages_about_url'
3 tests, 2 assertions, 0 failures, 1 errors, 0 skips
Error message if the URL to the About page cannot be found. Try modifying the routing file.
config/routes.rb
Rails.application.routes.draw do
get 'static_pages/home'
get 'static_pages/help'
get 'static_pages/about'← Add
root 'application#hello'
end
Test run
Terminal
$ rails test
AbstractController::ActionNotFound:
The action 'about' could not be found for StaticPagesController
Error message if there is no about action on the StaticPages controller. Try adding the about action.
app/controllers/static_pages_controller.rb
class StaticPagesController < ApplicationController
def home
end
def help
end
def about ← added
end ← added
end
Test run
Terminal
$ rails test
ActionController::UnknownFormat: StaticPagesController#about
is missing a template for this request format and variant.
Error message if there is no template (view). Create a view file with the following command or right-click.
Terminal
$ touch app/views/static_pages/about.html.erb
Test run
Terminal
$ rails test
3 tests, 3 assertions, 0 failures, 0 errors, 0 skips
The test is complete because it became 0 errors! !!
Refactor your code now that the tests are complete (This time it's done because there is no code to refactor)
This is called the "red / green / REFACTOR" cycle.
Recommended Posts