这个问题可能有一个简单的答案,但我找不到任何将 Roda 与 RSpec3 一起使用的示例,因此很难排除故障。
我正在使用 Marston 和 Dees “Effective Testing w/RSpec3”一书,它使用 Sinatra 而不是 Roda。我在将对象传递给 时遇到困难API.new
,并且从书中看,这适用于 Sinatra,但当我替换 Roda 时出现“参数数量错误”错误而失败。
根据我是否传递带有super
或不带有参数的参数super()
,错误切换以指示失败发生在初始化方法或规范中对 Rack::Test::Methods 的调用中。
我在 Rack::Test 中看到,在 Github repo README 中,我可能不得不使用Rack::Builder.parse_file("config.ru")
,但这并没有帮助。
以下是 rspec 在super
不使用括号时显示的两个错误:
失败:
1) MbrTrak::API POST /users when the user is successfully recorded returns the user id
Failure/Error: post '/users', JSON.generate(user)
ArgumentError:
wrong number of arguments (given 1, expected 0)
# ./spec/unit/app/api_spec.rb:21:in `block (4 levels) in <module:MbrTrak>'
使用时super()
:
1) MbrTrak::API POST /users when the user is successfully recorded returns the user id
Failure/Error: super()
ArgumentError:
wrong number of arguments (given 0, expected 1)
# ./app/api.rb:8:in `initialize'
# ./spec/unit/app/api_spec.rb:10:in `new'
# ./spec/unit/app/api_spec.rb:10:in `app'
# ./spec/unit/app/api_spec.rb:21:in `block (4 levels) in <module:MbrTrak>'
这是我的 api_spec.rb:
require_relative '../../../app/api'
require 'rack/test'
module MbrTrak
RecordResult = Struct.new(:success?, :expense_id, :error_message)
RSpec.describe API do
include Rack::Test::Methods
def app
API.new(directory: directory)
end
let(:directory) { instance_double('MbrTrak::Directory')}
describe 'POST /users' do
context 'when the user is successfully recorded' do
it 'returns the user id' do
user = { 'some' => 'user' }
allow(directory).to receive(:record)
.with(user)
.and_return(RecordResult.new(true, 417, nil))
post '/users', JSON.generate(user)
parsed = JSON.parse(last_response.body)
expect(parsed).to include('user_id' => 417)
end
end
end
end
end
这是我的 api.rb 文件:
require 'roda'
require 'json'
module MbrTrak
class API < Roda
def initialize(directory: Directory.new)
@directory = directory
super()
end
plugin :render, escape: true
plugin :json
route do |r|
r.on "users" do
r.is Integer do |id|
r.get do
JSON.generate([])
end
end
r.post do
user = JSON.parse(request.body.read)
result = @directory.record(user)
JSON.generate('user_id' => result.user_id)
end
end
end
end
end
我的 config.ru 是:
require "./app/api"
run MbrTrak::API