Running custom Ruby with Cypress

I've been using Cypress on a recent project to do end-to-end testing. From the brief introduction I've had so far, I'm impressed. The debugging experience seems like it's going to be considerably better than with tests written using Capybara. Capybara is great, but Cypress's visual debugging is hard to compete against.

Running custom Ruby

This project uses CypressOnRails to build a bridge between tests running within Cypress and Ruby-land, where the Rails app lives. In one particular test I wanted to turn a feature switch on and off (using Flipper). This required me calling some Ruby code from the Cypress test.

1
Flipper.enable(:new_feature)

This is possible through cy.appEval added by CypressOnRails.

1
2
3
4
5
6
7
it('Tests something with a feature switch turned on', function() {
  cy.appEval("Flipper.enable(:new_feature)").then(() => {
    cy.visit('/a/page')
    // select some elements
    // assert some things
  })
})

Making it reusable

Cypress supports adding functions that can be re-used inside the spec/cypress/support/commands.js file.

1
2
3
4
5
6
7
Cypress.Commands.add('enableFeature', function (flag) {
  cy.appEval('Flipper.enable(:' + flag + ')')
});

Cypress.Commands.add('disableFeature', function (flag) {
  cy.appEval('Flipper.disable(:' + flag + ')')
);

Now we can call these functions throughout all our tests.

1
2
3
4
5
6
7
8
9
it('Tests something with a feature switch turned on', function() {
  cy.enableFeature('new_feature') // Turn it on

  cy.visit('/a/page')
  // select some elements
  // assert some things

  cy.disableFeature('new_feature') // Turn it off again
})