2016-04-29 16 views
1

我下面的railstutorial by Michael Hartl,我不明白,在第5章測試失敗的原因。本書使用minitest框架,但我決定使用RSpec。爲此,我刪除了測試文件夾,並在我的Gemfile中包含rspec-rails,然後運行軟件包安裝和rails g rspec:install以生成我的spec文件夾。但是,有些測試我覺得使用minitest語法運行很方便,如static_pages_controller_spec.rb文件中的assert_select。這裏是我的規格文件看起來像:未定義的方法「文件」的零:NilClass在運行Rails的教程使用RSpec

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)出現在各失敗的測試。

我該如何解決?有什麼我做錯了嗎?

回答

0

這樣做的原因錯誤是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

相關問題