Introduction to Testing and Troubleshooting Basics

Let's write some more Cypress tests in this lesson.

In the last chapter, we focused on end-to-end testing with Cypress. We installed Cypress, wrote our first test with Cypress, and became familiar with the commands.

In this chapter, we’ll apply Cypress testing to the rest of our Hotwire and React pages and look at some ways to get more information in Cypress and in a browser. We’re also going to talk about some ways to troubleshoot tests and code in the browser.

Writing more Cypress tests

Let’s continue our Cypress tests. In the last chapter, we wrote a test that shows that our add favorite functionality works. Now let’s make a test to show that our remove favorite functionality also works.

We could simply add more lines to the existing test to continue that scenario with the removal of favorite functionality. While this may seem like a good option, longer tests like that tend to be more brittle, and a failing test gives us less information because the failure might be anywhere along the sequence of the test.

In order to get a test to a state where we can remove a favorite, we must again log a user in and add a favorite. Ideally, we’d be able to start the test in that state. The cypress-rails gem is deliberately structured without a built-in mechanism to trigger test-specific Rails data setup from within a Cypress test, though.

Instead, what cypress-rails expects us to do is write test-specific Rails controller code and invoke it from our tests using cy.request. Loading data from a controller has some advantages. It clearly places the responsibility for setting up data in a regular Rails process that does regular Rails things and is, therefore, easier to understand. Also, it separates the test and the data in a way that if we were ever to need to either move Cypress to its own code repository or change the server from Rails, we could do so with minimal changes to the test itself.

Here’s what that looks like in code. We only need a controller that will provide a home for test setup:

Get hands-on with 1200+ tech skills courses.