O'Reilly logo

Effective Testing with RSpec 3 by Myron Marston, Ian Dees

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Refactoring

Both test cases have identical expressions setting up the ledger test double. You can remove the duplication by moving these into a common before hook. Place the following code just inside the first context block:

 let​(​:expense​) { { ​'some'​ => ​'data'​ } }
 
 before​ ​do
 allow​(ledger).to receive(​:record​)
  .with(expense)
  .and_return(RecordResult.new(​true​, 417, ​nil​))
 end

Now, remove the setup code from both examples:

 it​ ​'returns the expense id'​ ​do
  post ​'/expenses'​, JSON.generate(expense)
 
  parsed = JSON.parse(last_response.body)
 expect​(parsed).to ​include​(​'expense_id'​ => 417) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required