这是我对Sinatra的首次尝试。我构建了一个简单的经典应用程序,为此设置了RSpec,并使其正常运行。然后,我尝试以MVC方式进行模块化。即使该应用程序可在浏览器中运行,RSpec也会抛出一个NoMethodError
。我已经阅读了有关RSpec的Sinatra文档,还在SO中进行了很多搜索,但是我找不到错误所在。有什么线索吗?
提前非常感谢您。
这是我的相关文件:
config.ru
require 'sinatra/base'
Dir.glob('./{app/controllers}/*.rb') { |file| require file }
map('/') { run ApplicationController }
app.rb
require 'sinatra/base'
class ZerifApp < Sinatra::Base
# Only start the server if this file has been
# executed directly
run! if __FILE__ == $0
end
app / controllers / application_controller.rb
class ApplicationController < Sinatra::Base
set :views, File.expand_path('../../views', __FILE__)
set :public_dir, File.expand_path('../../../public', __FILE__)
get '/' do
erb :index
end
end
spec / spec_helper.rb
require 'rack/test'
# Also tried this
# Rack::Builder.parse_file(File.expand_path('../../config.ru', __FILE__))
require File.expand_path '../../app.rb', __FILE__
ENV['RACK_ENV'] = 'test'
module RSpecMixin
include Rack::Test::Methods
def app() described_class end
end
RSpec.configure { |c| c.include RSpecMixin }
spec / app_spec.rb
require File.expand_path '../spec_helper.rb', __FILE__
describe "My Sinatra Application" do
it "should allow accessing the home page" do
get '/'
expect(last_response).to be_ok
end
end
错误
My Sinatra Application should allow accessing the home page
Failure/Error: get '/'
NoMethodError:
undefined method `call' for nil:NilClass
# ./spec/app_spec.rb:5:in `block (2 levels) in <top (required)>'
我猜您正在遵循此食谱,对吗?
在described_class
这行:
def app() described_class end
在这种情况下,它是要测试的类ZerifApp
。像这样尝试:
def app() ZerifApp end
编辑
事实证明,以上答案是不正确的described_class
。我以为它是一个占位符-实际上,它是一个RSpec方法,它返回隐式主题的类,也就是说,正在测试的事物。
链接上的配方具有误导性,因为它建议编写describe
块的方式:
describe "My Sinatra Application" do
这是有效的RSpec,但未定义主题类。described_class
在此块的示例中执行将返回nil
。要使其工作,请替换describe模块:
describe ZerifApp do
现在described_class
将返回预期值(ZerifApp
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句