render_views返回NoMethodError

我目前正在阅读Michael Hartl的Ruby on Rails教程,在本教程的第3.2.2节中,他谈到了使用RSpec来测试页面的标题。 我的测试(我自己编写,遵循他的教程)一直未通过标题测试(它可以找到标签,但标题总是一个空白字符串),并且一些搜索谷歌告诉我,我需要包含函数render_views传递测试。 我的问题是无论我尝试什么,RSpec NoMethodErrorrender_views返回render_views 。 我试过的事情:

  • spec_helper.rb config.render_views
  • describe "Static Pages" do render_views ... end在spec文件中describe "Static Pages" do render_views ... end
  • describe "Static Pages" do RSpec::Rails::ViewRendering.render_views ... end在spec文件中describe "Static Pages" do RSpec::Rails::ViewRendering.render_views ... end

所有这些都返回NoMethodError

我没有完全遵循他的Gemfile,所以Ruby和相关gem的版本是:

  • Ruby:1.9.3-p125
  • 铁轨:3.2.9
  • rspec:2.12.0
  • rspec-rails:2.12.0
  • capycabra:2.0.1

我在Windows 7上使用RubyMine 4.5.4。在命令提示符下运行测试会返回相同的错误。 spec文件是static_pages_spec.rb ,位于spec/requests

我的static_pages_spec.rb的代码:

 require_relative '../spec_helper' describe "Static Pages" do #RSpec::Rails::ViewRendering.render_views, returns NoMethodError #render_views, returns NameError describe "Home Page" do it "should have the h1 'Sample App'" do visit '/static_pages/home' page.should have_selector('h1', :text => "Sample App") end it "should have the title 'Home'" do visit '/static_pages/home' page.should have_selector('title', :text => "Ruby on Rails Tutorial Sample App | Home") end end describe "Help Page" do it "should have the h1 'Help'" do visit '/static_pages/help' page.should have_selector('h1', :text => "Help") end it "should have the title 'Help'" do visit '/static_pages/help' page.should have_selector('title', :text => "Ruby on Rails Tutorial Sample App | Help") end end describe "About Page" do it "should have the h1 'About Us'" do visit '/static_pages/about' page.should have_selector('h1', :text => "About Us") end it "should have the title 'About Us'" do visit '/static_pages/about' page.should have_selector('title', :text => "Ruby on Rails Tutorial Sample App | About Us") end end end 

我的spec_helper.rb是在使用--no-test-framework创建项目后通过创建运行rails generate integration_test自动生成的spec_helper.rb ,并在config块中添加了这些行:

 # Fix NoMethodError for method 'visit' config.include Capybara::DSL config.include Capybara::RSpecMatchers 

编辑经过一些测试,我已经设法通过将capybara版本更改为1.1.2来进行测试,同时仍然使用rspec 2.12.0和rspec-rails 2.12.0 而不使用render_views。 虽然我很高兴测试正在通过,但它仍然无法解决缺少render_views方法的问题,如果我尝试使用它,它仍然会出现。

好吧,经过一些测试后,解决了缺少的render_views方法的神秘面纱。 要包含渲染视图方法,在spec_helper中调用config.render_views或在spec文件中调用spec_helper之前,需要在spec_helper显示config.include RSpec::Rails::ViewRendering

其次,关于测试通过或失败,问题似乎是在Capybara本身。 显然,似乎1.1.2和2.0.1中visit方法的实现方式与它返回的方式有很大不同; 即使在包含render_views ,测试仍然失败(不使用config.include Capybara::RSpecMatchers )。 使用它似乎可以提供对其实现的深入了解; RSpecMatchers关于使用RSpecMatchers的失败消息是它正在寻找CSS而不是HTML。 但是,我没有声称完全理解它失败的原因,所以如果有人能够告诉我为什么Capybara 2.0.1导致测试失败而1.1.2允许测试通过,那将是很好的。

Capybara 2.0要求所有测试都符合规范/function ,而不是规格/要求。

你可以在这里阅读所有相关内容。

我建议你坚持使用Hartl教程中提到的版本,至少在你的初学者时代。 将帮助您更快地完成本教程!