Broken controller tests after installing Capybara?

2019-03-05 02:59发布

问题:

I had a bunch of combined controller/view tests written with rspec. I added the Capybara gem and wrote some integrations tests which pass fine. The only problem is that now in all my controller tests, where I have

response.should have_selector("some selector")

rspec gives errors such as:

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

when I run controller tests. I'm guessing that Capybara is being used in my controller tests and has overwritten some Rspec methods. How can I fix this?

# 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

Here's an example of a failing test:

# 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

and it's associated error:

  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)>'

回答1:

You were probably using Webrat earlier, and has_selector? is a Webrat matcher. Capybaras doesn't have a has_selector matcher, it has a matcher called has_css. You may want to replace the "has_selector" with "has_css".



回答2:

Capybara helpers only works within requests specs. Either create a new request spec, or pass in :type => :request in the describe block part, like so:

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

I realize this question was asked a long time ago, but I thought I would share anyway. GLHF