How to test CRUD operations in Rails
11 March 2022 (Updated 25 April 2022)
A lot of the functionality in web applications boil down to CRUD operations (Create, Read, Update, Delete). If you can get good test coverage for these operations, you’re in a good place. Let’s consider how you can use feature tests to test that users can successfuly CRUD a Quote
resource.
How to organize feature tests
Here’s a possible folder structure:
├── spec
│ ├── features
│ │ ├── quotes
| | | └── quotes_index_spec.rb
| | | └── create_quote_spec.rb
| | | └── show_quote_spec.rb
| | | └── update_quote_spec.rb
| | | └── delete_quote_spec.rb
Let’s consider what each spec might look like:
Index spec
- Index page requires authentication (not always a requirement).
- Index page shows empty items message when there are no items.
- Index page only lists items belonging to user (not always a requirement).
- Index page shows correct number of items per page (not always a requirement).
Create spec
- Create page requires user to be authenticated.
- When form submission is invalid, validation errors are shown.
- When form submission is valid, resource is created.
- Success message is shown.
- User is redirected to some route (usually index route of resource).
- Resource is created in the database with the new attributes.
Show spec
- Only the resource’s owner can view the quote details (not always a requirement).
- User can view the show page.
Update spec
- Edit page requires user to be authenticated.
- Only the resource’s owner can view the edit page.
- Only the resource’s owner can update the resource (see this post for testing strategy approach).
- When form submission is invalid, validation errors are shown.
- When form submission is valid, resource is updated with new values.
- Success message is shown.
- User is redirected to some route (usually index route of resource).
- Resource is updated in the database with the new attributes.
Delete spec
- Only the resource’s owner can delete the resource.
- User can delete the resource.
- Success message is shown.
- User is redirected to some route (usually index route of resource).
- Resource is deleted from the database.
Tagged:
Rails testing
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment