0
0
Ruby on Railsframework~5 mins

System tests with Capybara in Ruby on Rails

Choose your learning style9 modes available
Introduction

System tests check how your whole app works from a user's view. Capybara helps you write these tests by simulating clicks, typing, and page visits.

You want to make sure a user can log in successfully.
You want to test if a form submits and shows a success message.
You want to check navigation between pages works as expected.
You want to verify that buttons and links behave correctly.
You want to catch bugs that happen only when the app runs fully.
Syntax
Ruby on Rails
require "application_system_test_case"

class ExampleTest < ApplicationSystemTestCase
  test "user can visit homepage" do
    visit root_path
    assert_selector "h1", text: "Welcome"
  end
end
Use visit to open a page by its path or URL.
Use assert_selector to check if an element with specific text is on the page.
Examples
This example shows how to visit the login page, fill in fields, and click a button.
Ruby on Rails
visit login_path
fill_in "Email", with: "user@example.com"
fill_in "Password", with: "secret"
click_button "Log in"
Checks if the page shows the success message after login.
Ruby on Rails
assert_text "Logged in successfully"
Clicks a link named 'Profile' and confirms the browser is on the profile page.
Ruby on Rails
click_link "Profile"
assert_current_path profile_path
Sample Program

This system test simulates a user visiting the login page, entering their email and password, clicking the login button, and then checking if a welcome message appears.

Ruby on Rails
require "application_system_test_case"

class LoginTest < ApplicationSystemTestCase
  test "user logs in successfully" do
    visit login_path
    fill_in "Email", with: "test@example.com"
    fill_in "Password", with: "password123"
    click_button "Log in"

    assert_text "Welcome, test@example.com"
  end
end
OutputSuccess
Important Notes

System tests run slower than unit tests because they open a browser and simulate real user actions.

Use descriptive test names to explain what the test checks.

Capybara automatically waits for elements to appear, so you rarely need manual delays.

Summary

System tests check your app like a real user would.

Capybara helps write these tests with simple commands like visit, fill_in, and click_button.

Use assertions like assert_text to confirm expected page content.