nil:NilClass 的未定义方法 'document' 而 运行 Rails 的教程 rspec

undefined method 'document' for nil:NilClass while running Rails-tutorial with rspec

我正在关注 railstutorial by Michael Hartl,但我不明白 第 5 章 中测试失败的原因。这本书使用了 minitest 框架,但我决定使用 RSpec。为此,我删除了测试文件夹并在我的 Gemfile 中包含 rspec-rails 然后 运行 bundle install 和 rails g rspec:install 生成我的 spec 文件夹。但是,有一些我觉得方便的测试 运行 minitest 语法,例如 static_pages_controller_spec.rb 文件中的 assert_select。这是我的规范文件的样子:

require "rails_helper"

RSpec.describe StaticPagesController, type: :controller do
  describe "GET #home" do
    it "returns http success" do
      get :home
      expect(response).to have_http_status(:success)
    end
    it "should have the right title" do
      get :home
      assert_select "title", "Ruby on Rails Tutorial Sample App"
    end
  end

  describe "GET #help" do
    it "returns http success" do
      get :help
      expect(response).to have_http_status(:success)
    end
    it "should have the right title" do
      get :help
      assert_select "title", "Help | Ruby on Rails Tutorial Sample App"
    end
  end

  describe "GET #about" do
    it "returns http success" do
      get :about
      expect(response).to have_http_status(:success)
    end
    it "should have the right title" do
      get "about"
      assert_select "title", "About | Ruby on Rails Tutorial Sample App"
    end
  end
end

当我 运行 使用 RSpec 进行测试时,这就是我得到的失败错误:

StaticPagesController GET #home should have the right title
 Failure/Error: assert_select "title", "Ruby on Rails Tutorial Sample App"

 NoMethodError:
   undefined method `document' for nil:NilClass
# ./spec/controllers/static_pages_controller_spec.rb:11:in `block (3 levels)
in <top (required)>'

相同的错误消息 (No Method error) 出现在每个失败的测试中。

我该如何解决?是不是我做错了什么。

问题是 assert_selected 是一个 MiniTest 结构,而您使用的是 RSpec。您将需要使用 RSpec 机制来期待查看内容 https://relishapp.com/rspec/rspec-rails/v/3-4/docs/view-specs/view-spec or add capybara to your Gemfile and use the capybara matchers: https://gist.github.com/them0nk/2166525

此错误的原因是 RSpec 默认情况下不呈现控制器规格的视图。您可以像这样为特定的一组规范启用视图渲染:

describe FooController, type: :controller do
  render_views

  # write your specs
end

或者您可以通过在 RSpec 配置中的某处添加以下内容来全局启用它:

RSpec.configure do |config|
  config.render_views
end

有关详细信息,请参阅 https://www.relishapp.com/rspec/rspec-rails/v/2-6/docs/controller-specs/render-views