gpt4 book ai didi

ruby - 在 Sinatra 模块化应用程序中设置 RSpec

转载 作者:数据小太阳 更新时间:2023-10-29 07:52:39 24 4
gpt4 key购买 nike

这是我第一次尝试使用 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)>'

最佳答案

我猜你正在关注 this recipe ,对吗?

此行中的 described_class:

def app() described_class end

是被测类,在本例中为 ZerifApp。像这样尝试:

def app() ZerifApp end

编辑

事实证明,上述关于 described_class 所做的回答是不正确的。我假设它是一个占位符——实际上它是一个返回隐式主题类的 RSpec 方法,也就是说,被测试的东西。

链接中的食谱具有误导性,因为它建议编写 describe block 的方式:

describe "My Sinatra Application" do

这是有效的 RSpec,但它没有定义主题类。在此 block 的示例中执行 described_class 将返回 nil。要使其工作,请替换 describe block :

describe ZerifApp do

现在 described_class 将返回预期值 (ZerifApp)

关于ruby - 在 Sinatra 模块化应用程序中设置 RSpec,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25133321/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com