How Testing Rails App with Rspec and Capybara

waliyullah adetona
2 min readMay 14, 2021

Capybara is a web-based test automation software that runs

test for user stories operate web application testing for behavior-driven software development. Written in the Ruby programming language.

Capybara can mimic the actions of real users interacting with web-based applications. It can receive pages, parse the HTML and submit forms.

Benefits

Setup is not necessary for Rails and Rack applications. Works out of the box.

Intuitive API mimics the language an actual user would use.

Works in the backend to run your test fast headless mode to an actual browser with no changes to your tests.

Powerful synchronization features mean you never

have to wait for asynchronous processes to complete.

Setting Up

In your gem file add this gem

group :test do

gem ‘capybara’

gem ‘rspec’

gem ‘rspec-rails’

end

Then bundle install

While testing the Rails app, add this line to your test helper file:

require ‘capybara/rails’

require ‘capybara/rspec’

Put your Capybara specs in spec/features or

if you have your Capybara specs in a different directory,

then tag the example groups with type: :feature depending on which type of test you’re writing.

For example to test a file User, you can type this to your terminal to generate the spec file

Rails g rspec:features users

Its create `spec/features/users_spec.rb`

Navigate to the spec file to the file generated to see the file spec/features/users_spec.rb

Require “rails_helper”

Spec/features/user_spec.rb

Rspec.feature “Users” type: :feature do

Pending ”add some examples to (or delete) #{__FILE__}”

end

So you can start to write your test for example

describe “Users”, type: :feature do

it “create new user” do

visit ‘/sessions/new’

within(“#session”) do

fill_in ‘name’, with: ‘taiwo’

fill_in ‘Password’, with: ‘password’

end

click_button ‘Sign in’

expect(page).to have_content ‘Success’

end

Then you can test your code by running rspec on the terminal

The beauty of capybara is that you can even test for a specific line

Take for example

You can type

Respec spec/features.users_spec.rb:5

It will only test for the line specified.

Conclusion

Using caybara with rspec makes testing

of rails app easier to setup for testing with efficient results

Capybara helps you test web applications by simulating

how a real user would interact with your app.

Summary

Create Acceptance Tests or Feature Tests to extend your automated tests with browser testing. It can help tests some areas that cannot be accessible with other types of tests.

--

--

waliyullah adetona

A software developer, Fullstack, React,ruby on rails,Postgres,javascript