mirror of
https://github.com/jbranchaud/til
synced 2026-01-02 22:58:01 +00:00
Add Use Tap For Better Test Data Setup as a ruby til
This commit is contained in:
@@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
|
||||
For a steady stream of TILs from a variety of rocketeers, checkout
|
||||
[til.hashrocket.com](https://til.hashrocket.com/).
|
||||
|
||||
_837 TILs and counting..._
|
||||
_838 TILs and counting..._
|
||||
|
||||
---
|
||||
|
||||
@@ -694,6 +694,7 @@ _837 TILs and counting..._
|
||||
- [Up And Down With Integers](ruby/up-and-down-with-integers.md)
|
||||
- [Use A Case Statement As A Cond Statement](ruby/use-a-case-statement-as-a-cond-statement.md)
|
||||
- [Use dotenv In A Non-Rails Project](ruby/use-dotenv-in-a-non-rails-project.md)
|
||||
- [Use Tap For Better Test Data Setup](ruby/use-tap-for-better-test-data-setup.md)
|
||||
- [Using BCrypt To Create And Check Hashed Passwords](ruby/using-bcrypt-to-create-and-check-hashed-passwords.md)
|
||||
- [What To Do When You Don't Rescue](ruby/what-to-do-when-you-dont-rescue.md)
|
||||
- [Who Are My Ancestors?](ruby/who-are-my-ancestors.md)
|
||||
|
||||
35
ruby/use-tap-for-better-test-data-setup.md
Normal file
35
ruby/use-tap-for-better-test-data-setup.md
Normal file
@@ -0,0 +1,35 @@
|
||||
# Use Tap For Better Test Data Setup
|
||||
|
||||
I often use RSpec's `let` statement to set up some test data.
|
||||
|
||||
```ruby
|
||||
let(:order) { create(:order, name: "My Order") }
|
||||
```
|
||||
|
||||
Often times, realistic test data requires setting up peripheral data as well.
|
||||
|
||||
```ruby
|
||||
let(:order) do
|
||||
order = create(:order, name: "My Order")
|
||||
create(:item, name: "Burger", order: order, price: 4.99)
|
||||
create(:item, name: "Fries", order: order, price: 2.99)
|
||||
order
|
||||
end
|
||||
```
|
||||
|
||||
This can get hard to read as the subject of the `let` gets obscured. It is also
|
||||
clumsy that we have to end with returning the `order`. This can be cleaned up
|
||||
with the use of [`#tap`](https://devdocs.io/ruby~2.5/object#method-i-tap).
|
||||
|
||||
```ruby
|
||||
let(:order) do
|
||||
create(:order, name: "My Order").tap do |order|
|
||||
create(:item, name: "Burger", order: order, price: 4.99)
|
||||
create(:item, name: "Fries", order: order, price: 2.99)
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
The block notation and indentation make it clear that the `order` is what is
|
||||
getting created. Meanwhile, the interior of the block gives us a designated
|
||||
area to do what we need to with the newly-created `order` instance.
|
||||
Reference in New Issue
Block a user