我正在关注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
。以下是我的spec文件的样子:
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 :(得分:1)
此错误的原因是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。
答案 1 :(得分:-1)
问题是assert_selected是一个MiniTest构造,而你正在使用RSpec。您将需要使用RSpec机制来期待视图内容https://relishapp.com/rspec/rspec-rails/v/3-4/docs/view-specs/view-spec或将capybara添加到您的Gemfile并使用capybara匹配器:https://gist.github.com/them0nk/2166525