Van*_*tin 5 minitest rspec-rails railstutorial.org ruby-on-rails-4
我正在关注railstutorial by Michael Hartl,但我不明白第 5 章中测试失败的原因。这本书使用了 minitest 框架,但我决定使用 RSpec。为此,我删除了 test 文件夹并将其包含rspec-rails在我的 Gemfile 中,然后运行 bundle install 并rails g rspec:install生成我的 spec 文件夹。但是,我觉得使用 minitest 语法运行一些测试很方便,例如assert_select在static_pages_controller_spec.rb文件中。这是我的规范文件的样子:
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
Run Code Online (Sandbox Code Playgroud)
当我使用 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)>'
Run Code Online (Sandbox Code Playgroud)
(No Method error)每个失败的测试中都会出现相同的错误消息。
我该如何解决?是不是我做错了什么。
出现此错误的原因是 RSpec 默认情况下不渲染控制器规格的视图。您可以为特定组的规格启用视图渲染,如下所示:
describe FooController, type: :controller do
render_views
# write your specs
end
Run Code Online (Sandbox Code Playgroud)
或者您可以通过将其添加到 RSpec 配置中的某个位置来全局启用它:
RSpec.configure do |config|
config.render_views
end
Run Code Online (Sandbox Code Playgroud)
请参阅https://www.relishapp.com/rspec/rspec-rails/v/2-6/docs/controller-specs/render-views了解更多信息。
| 归档时间: |
|
| 查看次数: |
1495 次 |
| 最近记录: |