0
0
Ruby on Railsframework~5 mins

Controller tests in Ruby on Rails

Choose your learning style9 modes available
Introduction

Controller tests check if your app's web pages and actions work correctly. They make sure the right pages show up and the right data is handled.

When you want to verify a web page loads successfully.
When you need to check if submitting a form triggers the correct action.
When you want to confirm redirects happen as expected.
When you want to test if the controller assigns the right data to views.
When you want to catch errors early before users see them.
Syntax
Ruby on Rails
test "description" do
  get :action_name
  assert_response :success
  assert_not_nil assigns(:variable)
end

Use get, post, patch, delete to simulate HTTP requests.

assert_response checks the HTTP status like success or redirect.

Examples
This test checks if the index page loads without errors.
Ruby on Rails
test "should get index" do
  get :index
  assert_response :success
end
This test submits data to create an item and checks if it redirects to the item's page.
Ruby on Rails
test "should redirect after create" do
  post :create, params: { item: { name: "Book" } }
  assert_redirected_to item_path(assigns(:item))
end
This test ensures the controller sets the @items variable for the view.
Ruby on Rails
test "should assign items" do
  get :index
  assert_not_nil assigns(:items)
end
Sample Program

This test file checks two things: the index page loads and the create action adds a book then redirects properly.

Ruby on Rails
require "test_helper"

class BooksControllerTest < ActionController::TestCase
  test "should get index" do
    get :index
    assert_response :success
    assert_not_nil assigns(:books)
  end

  test "should create book and redirect" do
    post :create, params: { book: { title: "Rails Guide" } }
    assert_redirected_to book_path(assigns(:book))
  end
end
OutputSuccess
Important Notes

Controller tests run fast and help catch mistakes early.

Use assigns(:variable) to check variables sent to views.

Remember to test both success and failure cases for actions.

Summary

Controller tests check if web requests work as expected.

Use HTTP verbs like get and post to simulate user actions.

Check responses, redirects, and assigned variables to ensure correct behavior.