Capybara 2.0 and rspec-rails — helpers don't w

2019-06-21 04:56发布

问题:

I'm trying to use a method from a helper module, but rspec doesn't seem to recognize helpers for tests under spec/features. Note that the only change to spec_helper.rb was adding require 'capybara/rspec'.

I tried moving helper.rb to spec/support, spec/helpers, and spec/features (the directory that contains my tests), but no luck. The test keeps indicating that the helper method is undefined.

The only way to get it to "work" was by moving my test to a different directory, such as spec/integration. But now capybara won't work (visit undefined) because it's not in spec/features.

Here's my helper module (authentication_helper.rb):

module AuthenticationHelper
    def sign_in_as!(user)
        visit '/users/sign_in'
        fill_in "Email", with: user.email
        fill_in "Password", with: "password"
        click_button "Sign in"
        page.should have_content("Signed in successfully.")
    end
end

RSpec.configure do |c|
    c.include AuthenticationHelper, type: :request
end

回答1:

put this helper file in spec/support/

and this line spec_helper.rb

  # Requires supporting ruby files with custom matchers and macros, etc,
  # in spec/support/ and its subdirectories.
  Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }