I'm trying to use Rspec with capybara-webkit on a Rails 4 project and I'm getting an error to go with Capybara.default_host not being set properly.
The webkit_server is installed properly and is in PATH.
I've added the following gems to Gemfile:
group :test do
gem 'rspec-rails', "~> 2.12"
gem 'factory_girl'
gem 'capybara', '2.0.3' # capybara-webkit works with this version
gem 'capybara-webkit'
gem 'database_cleaner', :git => 'git://github.com/bmabey/database_cleaner.git'
gem 'email_spec'
end
My spec_helper.rb contains amongst other things:
require 'capybara'
require "capybara-webkit"
RSpec.configure do |config|
config.include(EmailSpec::Helpers)
config.include(EmailSpec::Matchers)
config.include Capybara::DSL, :type => :request
config.before(:suite) do
DatabaseCleaner.strategy = :truncation
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.start
end
end
Capybara.default_host = '127.0.0.1:3001'
Capybara.run_server = true
Capybara.javascript_driver = :webkit
Here is my test:
require 'spec_helper'
feature 'A feature' do
include Capybara::DSL
scenario 'first scenario', :js => true do
visit login_url
page.current_url.should eq('http://127.0.0.1:3001/login')
...
end
end
The error I'm getting is:
[16:40:24] paul@Pro2:web $ rspec spec/features/my_spec.rb
Run options: include {:locations=>{"./spec/features/my_spec.rb"=>[165]}}
F
Failures:
1) A feature - first scenario
Failure/Error: page.current_url.should eq('http://127.0.0.1:3001/login')
expected: "http://127.0.0.1:3001/login"
got: "http://example.iana.org/"
(compared using ==)
# ./spec/features/my_spec.rb:8:in `block (2 levels) in <top (required)>'
Finished in 1.69 seconds
1 example, 1 failure
Failed examples:
rspec ./spec/features/my_spec.rb:8 # A feature - first scenario
Randomized with seed 54529
Looks like it's using example.org as the hostname which is the default for the test environment.
Any suggestions?
UPDATE: Turns out this is not a bug but it's by design. The solution is to never use *_url but *_path (absolute vs. relative):
visit login_path
page.current_path.should eq(login_path)
This problem is not specific to Rails 4. I met this problem before in Rails 3.
I tried several settings but finally found the best solution is to change all url
to path
. For example:
visit login_path
page.current_path.should eq('/login')
Actually we don't need adding host to make this test meaningful. By this way your tests will not depend on any server they are running. No matter yours, your peers, CI servers etc.