【问题标题】:Broken controller tests after installing Capybara?安装 Capybara 后控制器测试损坏?
【发布时间】:2011-03-22 08:40:22
【问题描述】:

我有一堆用 rspec 编写的组合控制器/视图测试。我添加了 Capybara gem 并编写了一些通过良好的集成测试。唯一的问题是,现在在我所有的控制器测试中,我都有

response.should have_selector("some selector")

rspec 给出如下错误:

NoMethodError:
       undefined method `has_selector?' for #<ActionController::TestResponse:0xa03e7ec>

当我运行控制器测试时。我猜 Capybara 正在我的控制器测试中使用,并且已经覆盖了一些 Rspec 方法。我该如何解决这个问题?

# gemfile.rb
group :test do
  gem 'rspec'
  gem "capybara"
  gem "launchy"
  gem 'factory_girl_rails', '1.0'
end

# spec_helper.rb
RSpec.configure do |config|
  config.include IntegrationSpecHelper, :type => :request
end

这是一个失败的测试示例:

# spec/controllers/books_controller_spec.rb
require 'spec_helper'

describe BooksController do
  render_views

  it "should have the right page title" do
    get :show, :id => @book.ean
    response.should have_selector("title", :content => "Lexicase | " + @book.title)
  end
end

这是相关的错误:

  1) BooksController GET 'show' should have the right page title
     Failure/Error: response.should have_selector("title", :content => "Lexicase | " + @book.title)
     NoMethodError:
       undefined method `has_selector?' for #<ActionController::TestResponse:0xa8488c0>
     # ./spec/controllers/books_controller_spec.rb:23:in `block (3 levels) in <top (required)>'

【问题讨论】:

  • 你能添加你失败的测试吗?

标签: ruby-on-rails ruby-on-rails-3 rspec capybara


【解决方案1】:

您之前可能使用过 Webrat,而 has_selector? 是一个 Webrat 匹配器。 Capybaras 没有 has_selector 匹配器,它有一个名为 has_css 的匹配器。您可能希望将“has_selector”替换为“has_css”。

【讨论】:

  • 无论如何,您对 Webrat 的看法是正确的。据我所知,有一个 has_selector? Capybara (rubydoc.info/github/jnicklas/capybara/master/Capybara/…) 中的方法,但它在页面方法而不是请求方法上。另一件事是,我认为我不能再像使用 webrat 那样使用“get :show”了。我必须改用 visit(book_path(@book.ean)) 。然而,访问只能通过设计发出获取请求,这使得它不适合控制器单元测试。我在这里遗漏了一个更大的问题。
  • 哈哈,事实证明,Capybara 和 Webrat 并不像我最初假设的那样相互排斥。问题解决了!
  • 我希望博主不要再将 Capybara 称为 Webrat 的替代品,或者至少用可能需要的代码更改来限定声明。在进行切换后,我必须进行许多小改动才能使我的代码正常工作。
  • 我也是..它不是一个替代品
【解决方案2】:

Capybara 助手仅适用于请求规范。要么创建一个新的请求规范,要么在描述块部分传入 :type => :request ,如下所示:

describe "test for the testing test", :type => :request do
  it "should work with capybara" do
    visit root_path
    click_link "Home"
    page.should WHATEVA
  end
end

我知道这个问题是很久以前提出的,但我想我还是会分享。 GLHF

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多