Visit method not found in my rspec

2019-01-07 10:55发布

问题:

My java web application is running on tomcat at http://localhost:8080/

Writing my first spec, home_spec:

require 'spec_helper'


describe "home" do

    it "should render the home page" do
       visit "/"

       page.should have_content("hello world")
    end

end

And running:

rspec

I get:

F

Failures:

  1) home should render the home page
     Failure/Error: visit "/"
     NoMethodError:
       undefined method `visit' for #<RSpec::Core::ExampleGroup::Nested_1:0x242870b7>
     # ./spec/home/home_spec.rb:7:in `(root)'

Finished in 0.012 seconds
1 example, 1 failure

Failed examples:

rspec ./spec/home/home_spec.rb:6 # home should render the home page

Shouldn't this work because I have included capybara in the spec_helper?

How will it know to visit the correct url? what if my url is localhost:3030 or localhost:8080?

My gemfile:

source 'http://rubygems.org'

gem "activerecord"
gem "rspec"
gem "capybara"
gem "activerecord-jdbcmysql-adapter"

My spec_helper:

require 'capybara/rspec'

回答1:

Regarding to rspec issues (https://github.com/rspec/rspec-rails/issues/360)

you should put

config.include Capybara::DSL

in spec_helper.rb, inside the config block.



回答2:

The default directory that Capybara::RSpec now looks at to include the Capybara::DSL and Capybara::RSpecMatchers is changed from requests to features.

After I renamed my requests directory to features I got the matcher and DSL methods available again without having to explicitly include them.

See the following commit



回答3:

Also make sure your tests are in the /spec/features directory. According to rspec-rails and capybara 2.0, Capybara v2 and higher will not be available by default in RSpec request specs. They suggest to "...move any tests that use capybara from spec/requests to spec/features."



回答4:

By default the capybara DSL is included automatically if the file is in spec/requests, spec/integration or if the example group has :type => :request.

Because your file is in spec/home the capybara helpers aren't being included. You can either conform to one of the patterns above or adding include Capybara::DSL should also do the trick (you might also need to replicate some of the before(:each) stuff that would be setup.)



回答5:

First check it out

If you are not success,

Add this code your end of the your spec helper actually out of the RSpec.configure block as well

module ::RSpec::Core
  class ExampleGroup
    include Capybara::DSL
    include Capybara::RSpecMatchers
  end
end


回答6:

1) Add to ‘rails_helper’ config:

config.include Capybara::DSL
config.include Capybara::RSpecMatchers

And comment out the `require 'spec_helper'` line.

2) Add to 'spec_helper':

require 'rails_helper'