service objects in rails tests - factory_girl replacement
TRANSCRIPT
Service objects as a way of testing Rails apps
@andrzejkrzywda @arkency
In love/hate relationship with Rails, since 2004
Service objects
The things you call from your controllers
Rails is not your app Your app is below controllers
Most of the things without HTTP
AddProductToCart ChangeAmount
CreateNewBlogPost PublishBlogPost
AssignTestToPupils CreateNewKlass CheckoutOrder LogTimeEntry
ChangeInsurancePolicy
http://blog.arkency.com/2014/02/rails-refactoring-the-aha-moments/
Things that “do” something
Query objects - read the system
ListOfOrders UserQuery
PupilsInKlass BlogPostsByAuthor
Reads are easy Commands are more
difficult
Rails-way is good for Reads
Rails-way is not ideal for Commands
Testing
System tests vs
Unit tests
Good tests tell a story
1. User adds a product to the cart 2. User looks at the cart to see the current total amount
3. User changes the amount 4. User goes to checkout
How to setup the state?
factory_girl
Service objects in tests
What makes a good unit?
Unit == a set of service objects
scenario == service objects
Wins?
hides implementation details
tests in sync with production code
Easy to write
Fast
Problems?
Tests are one layer below !
Easy to make mistakes when calling services from controllers
Not so easy to extract services from an existing,
legacy Rails codebase
Examples
http://blog.arkency.com/2014/06/setup-your-tests-with-services/
Thanks!