Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
C

cypress-rails

> 编程语言
Open source

Helps you write Cypress tests of your Rails app

329 stars0 likes1 views
WebsiteGitHub

About

Helps you write Cypress tests of your Rails app

cypress-rails

This is a simple gem to make it easier to start writing browser tests with Cypress for your Rails apps, regardless of whether your app is server-side rendered HTML, completely client-side JavaScript, or something in-between.

Installation

tl;dr:

  1. Install the npm package cypress
  2. Install this gem cypress-rails
  3. Run rake cypress:init

Installing Cypress itself

The first step is making sure Cypress is installed (that's up to you, this library doesn't install Cypress, it just provides a little Rails-specific glue).

If you're on newer versions of Rails and using webpacker for your front-end assets, then you're likely already using yarn to manage your JavaScript dependencies. If that's the case, you can add Cypress with:

bash
$ yarn add --dev cypress

If you're not using yarn in conjunction with your Rails app, check out the Cypress docs on getting it installed. At the end of the day, this gem just needs the cypress binary to exist either in ./node_modules/.bin/cypress or on your PATH.

Installing the cypress-rails gem

Now, to install the cypress-rails gem, you'll want to add it to your development & test gem groups of your Gemfile, so that you have easy access to its rake tasks:

ruby
group :development, :test do
  gem "cypress-rails"
end

Once installed, you'll want to run:

bash
$ rake cypress:init

This will override a few configurations in your cypress.config.js configuration file.

Usage

Develop tests interactively with cypress open

When writing tests with Cypress, you'll find the most pleasant experience (by way of a faster feedback loop and an interactive, easy-to-inspect test runner) using the cypress open command.

When using Rails, however, you'll also want your Rails test server to be running so that there's something for Cypress to interact with. cypress-rails provides a wrapper for running cypress open with a dedicated Rails test server.

So, by running:

bash
$ rake cypress:open

Any JavaScript files added to cypress/integration will be identified by Cypress as tests. Simply click a test file in the Cypress application window to launch the test in a browser. Each time you save the test file, it will re-run itself.

Run tests headlessly with cypress run

To run your tests headlessly (e.g. when you're in CI), you'll want the run command:

bash
$ rake cypress:run

Managing your test data

The tricky thing about browser tests is that they usually depend on some test data being available with which to exercise the app efficiently. Because cypress is a JavaScript-based tool and can't easily manipulate your Rails app directly, cypress-rails provides a number of hooks that you can use to manage your test data.

By default, cypress-rails runs your app inside a database transaction and rolls it back between tests, much like a Rails system test. Every thread serving your app shares that one transaction, so whatever your tests create is undone on the next reset.

Here's what a config/initializers/cypress_rails.rb initializer might look like:

ruby
return unless Rails.env.test?

CypressRails.hooks.before_server_start do
  # Called once, before either the transaction or the server is started
end

CypressRails.hooks.after_transaction_start do
  # Called after the transaction is started (at launch and after each reset)
end

CypressRails.hooks.after_server_start do
  # Called once, after the server has booted
end

CypressRails.hooks.after_state_reset do
  # Triggered after `/cypress_rails_reset_state` is called
end

CypressRails.hooks.before_server_stop do
  # Called once, at_exit
end

(You can find an example initializer in this repo.)

The gem also provides a special route on the test server: /cypress_rails_reset_state. Each time it's called, cypress-rails does two things before responding:

  • If CYPRESS_RAILS_TRANSACTIONAL_SERVER is enabled, roll back the transaction and start a new one, resetting the database to how it was when the test run started, then trigger any after_transaction_start hooks
  • Trigger any after_state_reset hooks you've configured (regardless of the transactional server setting)

If a hook raises an error, the request fails with a 500 status and the error message, so the cy.request that triggered the reset fails too.

This way, you can easily instruct the server to reset its test state from your Cypress tests like so:

javascript
beforeEach(() => {
  cy.request('/cypress_rails_reset_state')
})

(Remember, in Cypress, before is a before-all hook and beforeEach is run between each test case!)

Turning off the transactional server

The transactional server funnels all of your app's database queries through a single connection, one at a time, just like a Rails system test. If your tests need your app to access the database concurrently, or your app does work that can't happen inside a transaction, set CYPRESS_RAILS_TRANSACTIONAL_SERVER=false and reset your data yourself in an after_state_reset hook. For example, with database_cleaner and Rails fixtures:

ruby
CypressRails.hooks.after_state_reset do
  DatabaseCleaner[:active_record].clean_with(:truncation)
  ActiveRecord::FixtureSet.reset_cache
  ActiveRecord::FixtureSet.create_fixtures(Rails.root.join("test/fixtures"), ["users", "posts"])
end

A few things to watch out for:

  • Don't use database_cleaner's :transaction strategy. It only opens a transaction on one of the server's database connections, so requests served on other connections save their changes for real, and those changes survive the reset. (On SQLite, the open transaction also makes other connections' writes fail with "database is locked" errors.)
  • Don't set DatabaseCleaner.strategy = ... at the top of an initializer. Before ActiveRecord has loaded, that assignment is silently ignored and database_cleaner's default :transaction strategy is used instead.
  • Truncation removes everything, including data loaded in before_server_start, so rebuild whatever your tests need in the hook. Call ActiveRecord::FixtureSet.reset_cache before reloading fixtures, or they'll be skipped as already loaded.

Configuration

Environment variables

The cypress-rails gem is configured entirely via environment variables. If you find yourself repeating a number of verbose environment variables as you run your tests, consider invoking the gem from a custom script or setting your preferred environment variables project-wide using a tool like dotenv.

  • CYPRESS_RAILS_DIR (default: Dir.pwd) the directory of your Rails project
  • CYPRESS_RAILS_CYPRESS_DIR (default: same value as rails_dir) the directory of your Cypress project
  • CYPRESS_RAILS_HOST (default: "127.0.0.1") the hostname to bind to
  • CYPRESS_RAILS_PORT (default: a random available port) the port to run the Rails test server on
  • CYPRESS_RAILS_BASE_PATH (default: "/") the base path for all Cypress's requests to the app (e.g. via cy.visit()). If you've customized your baseUrl setting (e.g. in cypress.config.js), you'll need to duplicate it with this environment variable
  • CYPRESS_RAILS_TRANSACTIONAL_SERVER (default: true) when true, starts a transaction before launching the server and rolls it back on every reset and on exit, so anything done during cypress open or cypress run is undone (similar to running a Rails system test). While it's enabled, all of the server's database access shares one connection. See Turning off the transactional server
  • CYPRESS_RAILS_CYPRESS_OPTS (default: none) any options you want to forward to the Cypress CLI when running its open or run commands.
  • CYPRESS_RAILS_SERVER_THREADS (default: "0:4") the min:max thread count passed to Puma's Threads: option when cypress-rails boots its own test server. Set to "1:1" for single-threaded mode. This is independent of your app's config/puma.rb, which cypress-rails does not read.

Example: Running a single spec from the command line

It's a little verbose, but an example of using the above options to run a single Cypress test would look like this:

$ CYPRESS_RAILS_CYPRESS_OPTS="--spec cypress/integration/a_test.js" bin/rake cypress:run

Example: Running your tests in Chromium

By default, Cypress will run its tests in its packaged Electron app, unless you've configured it globally. To choose which browser it will run from the command line, try this:

$ CYPRESS_RAILS_CYPRESS_OPTS="--browser chromium" bin/rake cypress:run

Initializer hooks

before_server_start

Pass a block to CypressRails.hooks.before_server_start to register a hook that will execute before the server or any transaction has been started. If you use Rails fixtures, it may make sense to load them here, so they persist across resets instead of being re-inserted each time.

after_server_start

Pass a block to CypressRails.hooks.after_server_start to register a hook that will execute after the server has booted (inside the transaction, if CYPRESS_RAILS_TRANSACTIONAL_SERVER is enabled).

after_transaction_start

If there's any custom behavior or state management you want to do inside the transaction (so that it's also rolled back each time a reset is triggered), pass a block to CypressRails.hooks.after_transaction_start. It runs when the server launches and after every reset, and only when CYPRESS_RAILS_TRANSACTIONAL_SERVER is enabled.

after_state_reset

Every time the test server receives an HTTP request at /cypress_rails_reset_state, the transaction will be rolled back and restarted (if CYPRESS_RAILS_TRANSACTIONAL_SERVER is enabled) and then the after_state_reset hook will be triggered, all before the request responds. To set up the hook, pass a block to CypressRails.hooks.after_state_reset.

before_server_stop

In case you've made any permanent changes to your test database that could pollute other test suites or scripts, you can use the before_server_stop to (assuming everything exits gracefully) clean things up and restore the state of your test database. If CYPRESS_RAILS_TRANSACTIONAL_SERVER is enabled, this runs after the transaction has been rolled back. To set up the hook, pass a block to CypressRails.hooks.before_server_stop.

Configuring Rails

Beyond the configuration options above, you'll probably also want to disable caching in your Rails app's config/environments/test.rb file, so that changes to your Ruby code are reflected in your tests while you work on them with rake cypress:open. (If either option is set to true, any changes to your Ruby code will require a server restart to be reflected as you work on your tests.)

To illustrate, here's what that might look like in config/environments/test.rb:

ruby
config.cache_classes = false
config.action_view.cache_template_loading = false

Setting up continuous integration

Circle CI

Nowadays, Cypress and Circle get along pretty well without much customization. The only tricky bit is that Cypress will install its large-ish binary to ~/.cache/Cypress, so if you cache your dependencies, you'll want to include that path:

…

Why use this?

Rails ships with a perfectly competent browser-testing facility called system tests which depend on capybara to drive your tests, most often with Selenium. All of these tools work, are used by lots of people, and are a perfectly reasonable choice

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Ruby

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言