这个问题可能有一个简单的答案,但我找不到与RSpec3一起使用Roda的任何示例,因此很难排除故障。
我正在使用马斯顿和迪斯“有效测试w/ RSpec3”的书,它使用辛纳特拉而不是罗达。我很难将一个对象传递给API.new,从书中看,这是对辛纳特拉有效的,但是当我替换罗达时,它失败了,出现了一个“错误的参数数”错误。
根据我是用super传递参数,还是向super()传递参数,错误切换指示失败发生在初始化方法或调用Rack::Test::方法时。
我在Rack::Test中看到了这一点,在Github中,我可能不得不使用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发布于 2022-06-10 00:17:27
roda已经定义了接收env作为参数的初始化方法,这个参数由类的app方法调用。看起来像这样
def self.app
...
lambda{|env| new(env)._roda_handle_main_route}
...
end应用程序的构造函数如下所示
def initialize(env)当您使用config.ru运行run MbrTrack::API时,实际上是在调用roda类的call方法,如下所示
def self.call(env)
app.call(env)
end 因为您已经重新定义了构造函数以接受散列位置参数,这将不再起作用,并且它会引发正在接收的错误。
ArgumentError:
wrong number of arguments (given 0, expected 1)现在,如果您想要使您的API类可配置,那么您想要解决的问题是尝试干式配置,它是伟大的dry-ruby宝石集合的一部分。
如果你想做别的事,可以随便问。
你已经很久没有发表你的问题了,所以希望你仍然会发现这是有帮助的。
https://stackoverflow.com/questions/71343634
复制相似问题