RSpec - 未初始化的常量,例如double

问题描述 投票:0回答:1

我正在使用TDD方法使用RSpec构建的小型API收到名称错误

NameError:
  uninitialized constant ExpenseTracker::API::Ledger

API.rb

require "sinatra/base"
require "json"

module ExpenseTracker
  class API < Sinatra::Base

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)
end

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

api_spec.rb

require_relative "../../../app/api"
require "rack/test"

module ExpenseTracker

RecordResult = Struct.new(:success?, :expense_id, :error_message)

RSpec.describe API do
include Rack::Test::Methods

def app
  API.new(ledger: ledger)
end

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

describe "POST /expense" do
  context "when the expenseis successfully recorded" do
    it 'returns the expense id'do
      allow(ledger).to receive(:record)
      .with(expense)
      .and_return(RecordResult.new(true, 417, nil))

    post '/expense', 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

以下是我得到的错误:

An error occurred while loading ./api_spec.rb.
Failure/Error:
  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

NameError:
  uninitialized constant ExpenseTracker::API::Ledger

/Users/Denis/Desktop/TDD/Effective_Testing_with_Rspec3/04-acceptance-specs/expense_tracker/app/api.rb:7:in `initialize'
/Users/Denis/Desktop/TDD/Effective_Testing_with_Rspec3/04-acceptance-specs/expense_tracker/app/api.rb:13:in `<class:API>'
/Users/Denis/Desktop/TDD/Effective_Testing_with_Rspec3/04-acceptance-specs/expense_tracker/app/api.rb:5:in `<module:ExpenseTracker>'
/Users/Denis/Desktop/TDD/Effective_Testing_with_Rspec3/04-acceptance-specs/expense_tracker/app/api.rb:4:in `<top (required)>'
./api_spec.rb:1:in `require_relative'
./api_spec.rb:1:in `<top (required)>'

我错过了什么吗?我试图通过分类帐:Ledger.new到app = API.new,但没有通过这个错误。

任何帮助或想法都会很棒!

api rspec sinatra bdd nameerror
1个回答
0
投票

好吧,在桌子上敲了很多头后,我想出了这个。

我不得不注释掉app = API.new,因为这还没有实现,每次我都会在规范中加载文件,它会让我误解。

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

现在到下一个失败的规格大声笑!

© www.soinside.com 2019 - 2024. All rights reserved.