Monday, March 24, 2014

How to test creating a new row in the database

A webpage has a form and a 'Create my account' button on it which is used to create a new user.

initial = User.count
click_button "Create my account"
final = User.count
expect(initial).to eq final

Here, User is the resultset, which includes all users.
We didn't fill in any data, and we are clicking the button to submit an empty form. We expect that a new user will not be created.
So the initial count of users should remain unchanged after clicking the "Create my account" button.

To test the case where the User is successfullly created, you fill in all the values, and check that the final count is 1 more than the intial count.

visit signup_path
fill_in "Name",         with: "Example User"
fill_in "Email",        with: ""
fill_in "Password",     with: "foobar"
fill_in "Confirmation", with: "foobar"
expect do
  click_button "Create my account" change(User, :count).by(1)

RSpec allows you to write the first test this way-

expect { click_button "Create my account" }.not_to change(User, :count)

No comments: