Easels App with Test Driven Development: Part 4
Master Test Driven Development with Ruby on Rails
The mantra of test driven development is red, green, refactor. When your tests initially fail, you'll see red errors until they pass and then you'll see green text. This exercise focuses on the crucial refactoring phase.
Tutorial Learning Objectives
Controller Refactoring
Learn to clean up repetitive code in the CompletionsController by extracting shared functionality into reusable private methods.
Test Code Optimization
Streamline test code by creating shared methods and eliminating duplication across feature specifications.
Authentication Implementation
Ensure proper user authentication before allowing to-do creation and completion actions.
Before vs After Controller Refactoring
| Feature | Before Refactoring | After Refactoring |
|---|---|---|
| Code Duplication | Todo.find repeated in create and destroy | Single get_todo private method |
| Method Structure | Separate logic in each method | Shared mark_todo method with time parameter |
| Maintainability | Changes require multiple updates | Single source of truth for shared logic |
| Reusability | Limited code reuse | Methods can be used by additional actions |
RSpec allows us to create separate files for storing custom methods that several tests share. Files must be in a separate folder called support, with feature-specific methods in spec/support/features/
Creating Shared Test Methods
Create Support Structure
Create spec/support/features directory structure for organizing shared test methods
Build Sign-in Method
Create sign_in_as method in Features module to handle user authentication in tests
Configure Rails Helper
Uncomment auto-require line and add config.include Features statement to load shared methods
Implement Todo Creation
Add create_todo method to eliminate repetitive form filling code across test files
At this juncture any old schmuck can create a to-do. Let's add a method that ensures a user must be signed in before they can add their tasks to our site.
Authentication Implementation
ApplicationController Method
Add authenticate! method that redirects unsigned users to the sign-in page, similar to the Devise gem pattern.
Before Action Filters
Implement before_action :authenticate! in both TodosController and CompletionsController to secure all actions.
Final Verification Steps
Ensure all five tests pass after refactoring and authentication changes
Use 'rails server' to launch the application and verify functionality in browser
Navigate to localhost and confirm users must sign in to access to-do functionality
Check that the To-Dos heading appears on all pages after moving it to application layout
Key Takeaways