How to use the test database with Capybara?

2019-02-21 20:06发布

问题:

I'm using RSpec, Spork, Capybara and Capybara Mechanic to write integration tests for a registration path that uses Facebook connect. It correctly navigates through registration, but the new users are created in my development database instead of the test database.

RSpec is setup to use the test environment and I've confirmed that any model methods I run in my spec all hit the test database, but all of the UI actions hit development.

Here's my test:

it "go through registration path" do
  print "RAILS_ENV: #{Rails.env}\n" # correctly prints 'test'
  print "1) #{User.count}\n" # correctly shows the user count in my test database (zero)

  Capybara.current_driver = :mechanize

  visit root_path
  click_link "register"

  # Fill in Facebook Connect form
  fill_in 'email', :with => "bob@example.com"
  fill_in 'pass', :with => "password"
  click_button "Log In"

  print "2) #{User.count}\n" # still shows zero users in the test database

end

After that test I can look at my development database and the new user has been created there.

I've tried setting up database_cleaner as well and that hasn't helped.

Anyone know what I need to do so that capybara will hit the test database?

rails 3.1.3

rspec 2.7.0

spork 0.9.0

capybara 1.1.0

capybara-mechanize 0.3.0.rc3

回答1:

The problem was that I had a separate development server running in parallel with the tests and the tests were defaulting to a the same address/port. I resolved this by adding the following to spec_helper.rb so Capybara would use a different port.

Capybara.run_server = true 
Capybara.server_port = 7000
Capybara.app_host = "http://localhost:#{Capybara.server_port}"