small medium large xlarge

15 Dec 2017, 22:14
Denis S Dujota (13 posts)

I am on CH5 trying to get test double to work, but i keep getting a name error. went through the code again to check if i missed anything and i cannot see where the issue is any help?


def initialize(ledger: # default value so callers can just say and get the default
  @ledger = ledger
  super() # rest of initialization from Sinatra

# Later, callers do this ledger:
app =

post '/expenses' do
  JSON.generate('expense_id' => 42)
  expense = JSON.parse(
  result = @ledger.record(expense)
  JSON.generate('expense_id' => result.expense_id)

get '/expenses/:date' do
end   end end `

below is the spec code: api_spec.rb

def app ledger)

let(:ledger) { instance_double('ExpenseTracker::Ledger') }

describe "POST /expenses" do
  context "when the expense is successfully recorded" do
    it 'returns the expense id' do
      expense = { 'some' => 'data' }
      allow(ledger).to receive(:record)
      .and_return(, 417, nil))

    post '/expenses', JSON.generate(expense)

    parsed = JSON.parse(last_response.body)
    expect(parsed).to include('expense_id' => 417)
    it 'responds with a 200 (OK)'

  context "when the expense fails validation" do
    it 'returns an error message'
    it 'responds with 422 (Unprocessable entity)'

end   end end`

what am i missing here?

15 Dec 2017, 21:43
Myron Marston (15 posts)

I believe the problem you are having is from this line:

app =

In the book, that was just meant to show how the API class will eventually be instantiated in non-test environments. It wasn’t meant to be code you put in your codebase at this point. The default argument allows callers to instantiate an API without specifying a ledger; however, for that to work, the referenced Ledger class must exist.

At this point, the Ledger class does not exist (intentionally so!) since we’re focusing on the API layer and are using a test double in place of a real ledger in our specs.

So, if you remove api = it should fix the problem.

If that doesn’t work, please provide the backtrace so we can dig into where the exception is being raised.


15 Dec 2017, 22:17
Denis S Dujota (13 posts)

Ok i see what you mean, removed it and got the spec to run.

note to self, just read the api_snippets.rb only implement the api.rb ones.

Thank you so much!

You must be logged in to comment