代码之家  ›  专栏  ›  技术社区  ›  Carles Jove i Buxeda

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

  •  4
  • Carles Jove i Buxeda  · 技术社区  · 11 年前

    这是我第一次尝试辛纳屈。我构建了一个简单的经典应用程序,为其设置了RSpec,并使其正常工作。然后,我尝试以MVC的方式进行模块化。即使该应用程序在浏览器中运行,RSpec仍会抛出 NoMethodError 。我已经阅读了关于RSpec的Sinatra文档,也在SO中搜索了很多,但我找不到bug在哪里。有线索吗?

    事先非常感谢。

    以下是我的相关文件:

    配置.ru

    require 'sinatra/base'
    
    Dir.glob('./{app/controllers}/*.rb') { |file| require file }
    
    map('/') { run ApplicationController }
    

    应用.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_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 }
    

    规范/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)>'
    
    2 回复  |  直到 11 年前
        1
  •  6
  •   zetetic    9 年前

    我猜你在跟踪 this recipe 对的

    这个 described_class 在这一行中:

    def app() described_class end
    

    在本例中,应该是被测试的类 ZerifApp 。请这样尝试:

    def app() ZerifApp end
    

    编辑

    事实证明,上面的答案是不正确的 描述的类别 做我假设它是一个占位符——实际上它是一种RSpec方法,它返回隐式主题的类,也就是说,被测试的对象。

    链接中的配方具有误导性,因为它建议编写 describe 块:

    describe "My Sinatra Application" do
    

    这是有效的RSpec,但它没有定义主题类。正在执行 描述的类别 在该块的示例中 nil 。要使其工作,请替换描述块:

    describe ZerifApp do
    

    现在 描述的类别 将返回预期值( Zerif应用程序 )

        2
  •  0
  •   Douglas G. Allen    10 年前

    https://pragprog.com/book/7web/seven-web-frameworks-in-seven-weeks

    它有一些源代码可以从中获得一些想法。

    这也有代码示例。 https://github.com/laser/sinatra-best-practices