DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Testing Strategies for Web Development Code Generated by LLMs
  • Testing Is Not About Finding Bugs
  • Frame Buffer Hashing for Visual Regression on Embedded Devices
  • How to Interpret the Number of Spring ApplicationContexts in Integration Tests

Trending

  • From "Vibe Coding" to Production: Setting Up an Evals Loop for Claude Agents
  • Testing Is Not About Finding Bugs
  • Amazon CodeWhisperer to Q Developer to Kiro: The Rise of Agentic Coding
  • Architecting Proactive IT: NinjaOne Remote Monitoring and Management
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Rails RSpec Setup

Rails RSpec Setup

Looking for a new testing framework that works well with BDD? Read on to learn about RSpec and the advantages it has for Ruby devs!

By 
Kristina Garcia Francisco user avatar
Kristina Garcia Francisco
·
Apr. 05, 18 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
11.0K Views

Join the DZone community and get the full member experience.

Join For Free

RSpec is an awesome tool for testing Rails apps. It is a hugely popular BDD-oriented (Behavior Driven Development) testing framework in the Ruby community.

It makes writing tests simpler, more expressive, and easier to maintain!

Getting Started

First, you'll need to install RSpec but you'll also need Database Cleaner to help hold things together and ensure a clean state during tests. Add the following gems to the  :test and  :development groups in your Gemfile and then run bundle install:

group :development, :test do
  gem "database_cleaner"
  gem "rspec-rails"
end

It is very common to use RSpec together with Capybara to improve your testing development.

Configuring RSpec

Before you can start with writing your RSpec tests, you will need to run rails generate rspec:install. This will create the following files:

create  .rspec
create  spec
create  spec/spec_helper.rb
create  spec/rails_helper.rb

Files such as, spec_helper.rb and rails_helper.rb contain the default RSpec set up with lots of comments. It is strongly recommended to read through all of those comments to get a good understanding of what each option does.

spec_helper.rb

The spec_helper.rb file is used to configure RSpec. The base configuration file, after uncommenting some useful configuration options, is written in the following way:

RSpec.configure do |config|
  config.expect_with :rspec do |expectations|
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end

  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end

  config.shared_context_metadata_behavior = :apply_to_host_groups
  config.filter_run_when_matching :focus
  config.disable_monkey_patching!

  if config.files_to_run.one?
    config.default_formatter = "doc"
  end

  config.profile_examples = 10

  config.order = :random
  Kernel.srand config.seed
end
  • expectations.include_chain_clauses_in_custom_matcher_descriptions = true - The chain method allows custom matcher descriptions and failure messages to include text for helper methods.
  • mocks.verify_partial_doubles = true - Partial doubles prevent you from stubbing any methods that don't already exist on an object; it typo-proofs your mocks.
  • config.shared_context_metadata_behavior = :apply_to_host_groups - Shared context metadata configures how RSpec treats metadata passed as part of a shared example group definition.
  • filter_run_when_matching - Filter run when matching allows you to limit a spec run to individual examples or groups you tagged with :focus metadata.
  • disable_monkey_patching! - Prevents RSpec from monkey patching; makes objects behave in tests as they would in "real" life.
  • default_formatter - Default formatter sets up the default format of your RSpec tests that will be used if no formatter has been set.
  • config.profile_examples - Profile examples print the slowest examples and example groups at the end of the spec run, but it slows down your suite.
  • config.order = :random and Kernel.srand config.seed - Configure tests to run in a random order. This helps to keep each test independent of one another.

rails_helper.rb

The rails_helper.rb file is used for specs which depend on Rails (mostly model and controller tests, but also on nearly every part of a Rails project).

rails_helper.rb requires spec_helper.rb to work.

require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'

ActiveRecord::Migration.maintain_test_schema!

RSpec.configure do |config|
  config.fixture_path = "#{::Rails.root}/spec/fixtures"
  config.use_transactional_fixtures = true
  config.infer_spec_type_from_file_location!
  config.filter_rails_from_backtrace!
end
  • fixture_path - File fixture is a normal file stored in spec/fixtures by default.
  • use_transactional_fixtures - Transactional fixtures allow records created for one test to be visible for the next test.
  • infer_spec_type_from_file_location! - Allows you to automatically tag specs in directories with matching type metadata so that they have relevant helpers available to them.
  • filter_rails_from_backtrace! - Backtrace filtering is used to filter out lines in backtraces that come from Rails gems in order to reduce the noise in test failure output.

Configuring the Database Cleaner

By configuring the Database Cleaner in your application, you make sure that tests start with a clean state. The only thing you need to do is to add the following to your RSpec.configure block in rails_helper.rb:

config.before(:suite) do
  DatabaseCleaner.clean_with(:truncation)
end

How to Run the Tests

Once everything is configured, you are ready to go! There are four ways to run your test:

  • Everything at once: bundle exec rspec.
    This runs all your tests.
  • One RSpec package: bundle exec rspec ./spec/models
    This runs all model specs.
  • One RSpec file at a time: bundle exec rspec ./spec/models/story_spec.rb.
    This runs only tests in the Story model.
  • One by one: bundle exec rspec ./spec/models/story_spec.rb:10
    This runs only tests on line 10 in the Story model.

In the same way, you can run tests on your controller.

Be careful! The more tests there are the longer it takes to compile them. Only run tests for what you really need! 

We hope this article helped you get your tests up and running! 

Testing

Published at DZone with permission of Kristina Garcia Francisco. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Testing Strategies for Web Development Code Generated by LLMs
  • Testing Is Not About Finding Bugs
  • Frame Buffer Hashing for Visual Regression on Embedded Devices
  • How to Interpret the Number of Spring ApplicationContexts in Integration Tests

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook