Ruby On Rails Lesson
Tests for User Signup
In the days before powerful web frameworks with full testing capabilities, testing was often painful and error-prone. For example, to test a signup page manually, we would have to visit the page in a browser and then submit alternately invalid and valid data, verifying in each case that the application’s behavior was correct. Moreover, we would have to remember to repeat the process any time the application changed. With RSpec
and Capybara, we will be able to write expressive tests to automate tasks that used to have to be done by hand. We’ve already seen how Capybara supports an intuitive web-navigation syntax. So far, we’ve mostly used visit to visit particular pages, but Capybara can do a lot more, including filling in the kind of fields we see in Figure 7.11 and clicking on the button. The syntax looks like this:
Our goal now is to write tests for the right behavior given invalid and valid signup information. Because these tests are fairly advanced, we’ll build them up piece by piece. If you want to see how they work (including which file to put them in), you can skip ahead to Listing 7.16.
Our first task is to test for a failing signup form, and we can simulate the submission of invalid data by visiting the page and clicking the button using click_button:
This is equivalent to visiting the signup page and submitting blank signup information (which is invalid). Similarly, to simulate the submission of valid data, we fill in valid information using fill_in:
The purpose of our tests is to verify that clicking the ‘‘Create my account’’ button results in the correct behavior, creating a new user when the information is valid and not creating a user when it’s invalid. The way to do this is to check the count of users, and under the hood our tests will use the count method available on every Active Record class, including User: