Skip to content

Instantly share code, notes, and snippets.

@ondrejbartas
Last active April 2, 2021 01:15
Show Gist options
  • Save ondrejbartas/446ddfdad497f94384b647b96bd6a32f to your computer and use it in GitHub Desktop.
Save ondrejbartas/446ddfdad497f94384b647b96bd6a32f to your computer and use it in GitHub Desktop.
How to setup Cypress on Rails apps

How to setup Cypress on Rails apps

You need to update circle.yml:

machine:
  node: # add node dependency
    version:
      7.4

environment:
  RAILS_ENV: test # Add this so rails app knows which environment to use for all tasks

dependencies:
  cache_directories:
    - /home/ubuntu/.cypress/Cypress
    - /home/ubuntu/.cache/yarn
  pre:
    - curl -o- -L https://yarnpkg.com/install.sh | bash
    - yarn global add gulp cypress-cli
  post:
    - cypress install

database:
  override:
    - bundle exec rake db:create db:schema:load db:seed # This is normal task you are doing (just add db:seed)
    - bundle exec rails s > $CIRCLE_ARTIFACTS/server.log 2>&1: # This task will start rails application in background
        background: true

test:
  override:
    - bundle exec rspec # run normal rspec command
    - cypress run --config videoRecording=false,screenshotOnHeadlessFailure=false || cypress run --config videoRecording=true,screenshotOnHeadlessFailure=true

general:
  artifacts: # store cypress artifacts
    - cypress/screenshots
    - cypress/videos

In Rails application is good to add controller for cleanup whole application and seed it again for every test of cypress:

# app/controllers/cleanup_controller.rb
class CleanupController < ApplicationController

  skip_before_action :verify_authenticity_token, only: :destroy
  def destroy
    tables = ActiveRecord::Base.connection.tables
    tables.delete 'schema_migrations'
    tables.each { |t| ActiveRecord::Base.connection.execute("TRUNCATE #{t} CASCADE") }
    Rails.application.load_seed
    render text: 'Truncated tables and seeded'
  end
end
# config/routes.rb

Rails.application.routes.draw do


  delete '/cleanup' => 'cleanup/destroy' if Rails.env.test?
end

and in cypress support to have command for cleanup:

// cypress/support/commands.js

Cypress.addParentCommand('cleanupApp', () => {
  cy.request('DELETE', 'http://localhost:3000/cleanup');
});


// and somewhere in main command (visitHome, etc.) add this call: 
cy.cleanupApp() // cleanup database and seed data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment