Rails 4:在 Capybara & Poltergeist 集成测试中存根

Rails 4: stubbing in a Capybara & Poltergeist integration test

我在 Rails 4 应用程序中使用 Capybara & Poltergeist 测试相当简单的规范时遇到问题。

规格如下:

feature 'Creating user groups', :devise, js: true do
  let(:panel) { create(:panel) }
  let(:admin) { create(:user, :admin) }

  before do
    login_as(admin)
    visit admin_panel_user_groups_path(panel)
    click_link 'New user group'
  end

  context 'successfully' do
    it 'admin can create a new user group' do
      fill_in 'User group', with: 'Some group'
      click_button 'Save'

      expect(page).to have_content('Your user group has been saved correctly')
    end
  end
end

规范最终调用了这个create方法,returns一个json响应format.js(这就是为什么我运行上面的规范js: true):

class Admin::UserGroupsController < AdminController
  respond_to :html, :json, :js, :csv
  before_action :set_panel

  def create
    respond_to do |format|
      @user_group = UserGroup.new(user_group_params.merge({panel_id: @panel.id}))
      if @user_group.save
        @user_group.refresh!
        format.js do
          render json: {
            responseType: 'modelSaved',
            object: @user_group
          }.to_json, status: 200
        end
      else
        format.js do
          render json: {
            responseType: 'error',
            object: @user_group
          }.to_json, status: 500
        end
      end
    end
  end
end

我已经在我的 rails_helper.rb 文件中设置了 Poltergeist:

require 'capybara/poltergeist'

RSpec.configure do |config|
  config.include Warden::Test::Helpers, type: :feature
  config.after(type: :feature) { Warden.test_reset! }
  Capybara.javascript_driver = :poltergeist
end

但是当我 运行 规范时收到以下错误消息:

Failure/Error: visit admin_panel_user_groups_path(panel)
WebMock::NetConnectNotAllowedError:
Real HTTP connections are disabled. Unregistered request: GET http://127.0.0.1:54553/__identify__ with headers {'Accept'=>'*/*', 'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'User-Agent'=>'Ruby'}

You can stub this request with the following snippet:

stub_request(:get, "http://127.0.0.1:54553/__identify__").
with(:headers => {'Accept'=>'*/*', 'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'User-Agent'=>'Ruby'}).
to_return(:status => 200, :body => "", :headers => {})

registered request stubs:

stub_request(:get, "/http:\/\/maps.googleapis.com\/maps\/api\/geocode\/json?components=country:US|postal_code:\d+/")
stub_request(:get, "https://freegeoip.net/json/123.123.123.123").
with(:headers => {'Accept'=>'*/*', 'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'User-Agent'=>'Ruby'})

我相信这是因为规范中不允许外部连接(这很好)。但是,在集成测试中存根外部请求是否有意义?我是否错误地配置了 Poltergeist 或错误地考虑了此测试?

提前致谢!

当 运行ning 功能测试时,你真的不应该启用 WebMock(它不能存根或阻止你正在使用的 "browser" 发出的请求,PhantomJS,无论如何,所以它不是真正保护您免受传出连接的影响)。所以你要么需要在运行宁功能测试

时允许连接
WebMock.allow_net_connect!

或至少允许连接到 AUT,在本例中是 运行 on 127.0.0.1

WebMock.disable_net_connect!(allow_localhost: true)