RSpec - 未初始化的常量,例如double
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了RSpec - 未初始化的常量,例如double相关的知识,希望对你有一定的参考价值。
我正在使用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,但没有通过这个错误。
任何帮助或想法都会很棒!
答案
好吧,在桌子上敲了很多头后,我想出了这个。
我不得不注释掉app = API.new,因为这还没有实现,每次我都会在规范中加载文件,它会让我误解。
# Later, callers do this ledger: Ledger.new
app = API.new()
现在到下一个失败的规格大声笑!
以上是关于RSpec - 未初始化的常量,例如double的主要内容,如果未能解决你的问题,请参考以下文章
尝试运行 rspec 时,我得到“未初始化的常量 ActiveModel”
尝试在Rails中设置rspec测试时获取未初始化的常量Faker :: String
RSpec:#<RSpec::Core::ExampleGroup::Nested_1:0x007fcc2f626d50> 的未定义方法“double”