1

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

  • config.render_viewsspec_helper.rb
  • describe "Static Pages" do render_views ... end在规范文件中
  • describe "Static Pages" do RSpec::Rails::ViewRendering.render_views ... end在规范文件中

他们都返回一个NoMethodError.

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

  • 红宝石:1.9.3-p125
  • 导轨:3.2.9
  • rspec:2.12.0
  • rspec-rails:2.12.0
  • 水豚:2.0.1

我在 Windows 7 上的 RubyMine 4.5.4 中工作。但是,在命令提示符下运行测试会返回相同的错误。规范文件位于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

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

# 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方法的问题,如果我尝试使用它,它仍然会出现。

4

2 回答 2

3

好吧,经过多一点测试,失踪render_views方法之谜就解决了。要包含渲染视图方法,显然config.include RSpec::Rails::ViewRenderingspec_helper调用或规范文件之前需要config.render_viewsspec_helperrender_views

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

于 2012-12-12T16:39:44.740 回答
0

Capybara 2.0 要求所有测试都在spec/features中,而不是在 spec/requests 中。

您可以在此处阅读所有相关信息。

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

于 2012-12-12T14:30:28.147 回答