Skip to content
Switch branches/tags
Go to file
Cannot retrieve contributors at this time


Build Status cypress-on-rails Gem Version

This project is sponsored by the software consulting firm ShakaCode, creator of the React on Rails Gem. We focus on React (with TS or ReScript) front-ends, often with Ruby on Rails or Gatsby. See our recent work and client engagement model. Feel free to engage in discussions around this gem at our Slack Channel or our forum category for Cypress.

Interested in joining a small team that loves open source? Check our careers page.

Need help with cypress-on-rails? Contact ShakaCode.

Totally new to Cypress?

Suggest you first learn the basics of Cypress before attempting to integrate with Ruby on Rails


Gem for using in Rails and Ruby Rack applications with the goal of controlling state as mentioned in Cypress Best Practices

It allows you to run code in the application context when executing cypress tests. Do things like:

  • use database_cleaner before each test
  • seed the database with default data for each test
  • use factory_bot to setup data
  • create scenario files used for specific tests

Has examples of setting up state with:

  • factory_bot
  • rails test fixtures
  • scenarios
  • custom commands



Add this to your Gemfile:

group :test, :development do
  gem 'cypress-on-rails', '~> 1.0'

Generate the boilerplate code using:

bin/rails g cypress_on_rails:install

# if you have/want a different cypress folder (default is cypress)
bin/rails g cypress_on_rails:install --cypress_folder=spec/cypress

# if you want to install cypress with npm
bin/rails g cypress_on_rails:install --install_cypress_with=npm

# if you already have cypress installed globally
bin/rails g cypress_on_rails:install --no-install-cypress

# to update the generated files run
bin/rails g cypress_on_rails:update

The generator modifies/adds the following files/directory in your application:

  • config/environments/test.rb
  • config/initializers/cypress_on_rails.rb used to configure Cypress on Rails
  • spec/cypress/e2e/ contains your cypress tests
  • spec/cypress/support/on-rails.js contains Cypress on Rails support code
  • spec/cypress/app_commands/scenarios/ contains your Cypress on Rails scenario definitions
  • spec/cypress/cypress_helper.rb contains helper code for Cypress on Rails app commands

If you are not using database_cleaner look at spec/cypress/app_commands/clean.rb. If you are not using factory_bot look at spec/cypress/app_commands/factory_bot.rb.

Now you can create scenarios and commands that are plain Ruby files that get loaded through middleware, the ruby sky is your limit.

Update your database.yml

When running cypress test on your local computer it's recommended to start your server in development mode so that changes you make are picked up without having to restart the server. It's recommended you update your database.yml to check if the CYPRESS environment variable is set and switch it to the test database otherwise cypress will keep clearing your development database.

For example:

  <<: *default
  database: <%= ENV['CYPRESS'] ? 'my_db_test' : 'my_db_development' %>
  <<: *default
  database: my_db_test


WARNING!!: cypress-on-rails can execute arbitrary ruby code Please use with extra caution if starting your local server on or running the gem on a hosted server


Getting started on your local environment

# start rails
CYPRESS=1 bin/rails server -p 5017

# in separate window start cypress
yarn cypress open 
# or for npm
node_modules/.bin/cypress open 
# or if you changed the cypress folder to spec/cypress
yarn cypress open --project ./spec

How to run cypress on CI

# setup rails and start server in background
# ...

yarn run cypress run
# or for npm
node_modules/.bin/cypress run 

Example of using factory bot

You can run your factory_bot directly as well

// spec/cypress/e2e/
describe('My First Test', () => {
  it('visit root', () => {
    // This calls to the backend to prepare the application state
      ['create_list', 'post', 10],
      ['create', 'post', {title: 'Hello World'} ],
      ['create', 'post', 'with_comments', {title: 'Factory_bot Traits here'} ] // use traits

    // Visit the application under test

    cy.contains('Hello World')

    // Accessing result
    cy.appFactories([['create', 'invoice', { paid: false }]]).then((records) => {

You can check the association docs on more ways to setup association with the correct data.

In some cases, using static Cypress fixtures may not provide sufficient flexibility when mocking HTTP response bodies. It's possible to use to generate Ruby hashes that can then be used as mock JSON responses:

FactoryBot.define do
  factory :some_web_response, class: Hash do
    initialize_with { attributes.deep_stringify_keys }

    id { 123 }
    name { 'Mr Blobby' }
    occupation { 'Evil pink clown' }
end => { 'id' => 123, 'name' => 'Mr Blobby', 'occupation' => 'Evil pink clown' })

This can then be combined with Cypress mocks:

describe('My First Test', () => {
  it('visit root', () => {
    // This calls to the backend to generate the mocked response
      ['build', 'some_web_response', { name: 'Baby Blobby' }]
    ]).then(([responseBody]) => {
      cy.intercept('', {
        body: responseBody

      // Visit the application under test

    cy.contains('Hello World')

Example of loading Rails test fixtures

# spec/cypress/app_commands/activerecord_fixtures.rb
require "active_record/fixtures"

fixtures_dir = ActiveRecord::Tasks::DatabaseTasks.fixtures_path
fixture_files = Dir["#{fixtures_dir}/**/*.yml"].map { |f| f[(fixtures_dir.size + 1)..-5] }

logger.debug "loading fixtures: { dir: #{fixtures_dir}, files: #{fixture_files} }"
ActiveRecord::FixtureSet.create_fixtures(fixtures_dir, fixture_files)
// spec/cypress/e2e/
describe('My First Test', () => {
  it('visit root', () => {
    // This calls to the backend to prepare the application state

    // Visit the application under test

    cy.contains('Hello World')

Example of using scenarios

Scenarios are named before blocks that you can reference in your test.

You define a scenario in the spec/cypress/app_commands/scenarios directory:

# spec/cypress/app_commands/scenarios/basic.rb
Profile.create name: "Cypress Hill"

# or if you have factory_bot enabled in your cypress_helper
CypressOnRails::SmartFactoryWrapper.create(:profile, name: "Cypress Hill")

Then reference the scenario in your test:

// spec/cypress/e2e/
describe('My First Test', () => {
  it('visit root', () => {
    // This calls to the backend to prepare the application state


    cy.contains('Cypress Hill')

Example of using app commands

Create a Ruby file in the spec/cypress/app_commands directory:

# spec/cypress/app_commands/load_seed.rb
load "#{Rails.root}/db/seeds.rb"

Then reference the command in your test with'load_seed'):

// spec/cypress/e2e/
describe('My First Test', () => {
  beforeEach(() => {'load_seed') })

  it('visit root', () => {


Experimental Features (matching npm package)

Please test and give feedback.

Add the npm package:

yarn add cypress-on-rails --dev

for VCR

This only works when you start the Rails server with a single worker and single thread


Add your VCR configuration to your cypress_helper.rb

require 'vcr'
VCR.configure do |config|
  config.hook_into :webmock

Add to your cypress/support/index.js:

import 'cypress-on-rails/support/index'

Add to your cypress/app_commands/clean.rb:

VCR.eject_cassette # make sure we no cassettes inserted before the next test starts
WebMock.disable! if defined?(WebMock)

Add to your config/cypress_on_rails.rb:

  c.use_vcr_middleware = !Rails.env.production? && ENV['CYPRESS'].present?


You have vcr_insert_cassette and vcr_eject_cassette available.

describe('My First Test', () => {
  beforeEach(() => {'load_seed') })

  it('visit root', () => {'clean') // have a look at cypress/app_commands/clean.rb

    cy.vcr_insert_cassette('cats', { record: "new_episodes" })

    cy.contains('Wikipedia has a recording of a cat meowing, because why not?')


    cy.contains('Wikipedia has a recording of a cat meowing, because why not?')

Usage with other rack applications

Add CypressOnRails to your

# an example
require File.expand_path('my_app', File.dirname(__FILE__))

require 'cypress_on_rails/middleware'
CypressOnRails.configure do |c|
  c.cypress_folder = File.expand_path("#{__dir__}/test/cypress")
use CypressOnRails::Middleware

run MyApp

add the following file to Cypress

// test/cypress/support/on-rails.js
// CypressOnRails: don't remove these commands
Cypress.Commands.add('appCommands', (body) => {
    method: 'POST',
    url: '/__cypress__/command',
    body: JSON.stringify(body),
    log: true,
    failOnStatusCode: true

Cypress.Commands.add('app', (name, command_options) => {
  cy.appCommands({name: name, options: command_options})

Cypress.Commands.add('appScenario', (name) => {'scenarios/' + name)

Cypress.Commands.add('appFactories', (options) => {'factory_bot', options)
// CypressOnRails: end

// The next is optional
beforeEach(() => {'clean') // have a look at cypress/app_commands/clean.rb


  1. Fork it ( )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request


JetBrains ScoutAPM
BrowserStack Rails Autoscale Honeybadger

The following companies support our open source projects, and ShakaCode uses their products!