gpt4 book ai didi

ruby-on-rails-4 - 未定义的方法 'document' 为 nil :NilClass while running Rails-tutorial with rspec

转载 作者:行者123 更新时间:2023-12-01 04:56:21 25 4
gpt4 key购买 nike

我正在关注 railstutorial by Michael Hartl ,我不明白 中测试失败的原因第5章 .这本书使用了 minitest 框架,但我决定使用 RSpec。为此,我删除了 test 文件夹并包含了 rspec-rails在我的 Gemfile 中,然后运行 ​​bundle install 和 rails g rspec:install生成我的规范文件夹。但是,有一些我觉得用 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

当我使用 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)出现在每个失败的测试中。

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

最佳答案

此错误的原因是默认情况下 RSpec 不呈现 Controller 规范的 View 。您可以为特定的一组规范启用 View 渲染,如下所示:

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想要查询更多的信息。

关于ruby-on-rails-4 - 未定义的方法 'document' 为 nil :NilClass while running Rails-tutorial with rspec,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36949205/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com