small medium large xlarge

Generic-user-small
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?

api.rb

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

# Later, callers do this ledger: Ledger.new
app = API.new()

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

get '/expenses/:date' do
  JSON.generate([])
end   end end `

below is the spec code: api_spec.rb

def app
  API.new(ledger: ledger)
end

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)
      .with(expense)
      .and_return(RecordResult.new(true, 417, nil))

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

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

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

end   end end`

what am i missing here?

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

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

app = API.new()

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 = API.new() 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.

Myron

Generic-user-small
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