ruby-on-rails - 使用 throw :async? 测试 Rails Controller 操作的正确方法是什么

标签 ruby-on-rails rspec capybara thin

我有一个在 Thin 上运行的 Rails 服务器和一个异步 Controller 操作。我想使用 RSpec 测试它,但出现错误:

 Failure/Error: get :access_token
     ArgumentError:
       uncaught throw :async

这是示例代码:

class SampleController < ApplicationController

  def sample
    EM.defer do
      render json: { response: 'Hello World' }

      request.env['async.callback'].call response
    end

    throw :async
  end

end

require 'spec_helper'

describe SampleController, :type => :controller do
  it "hello world" do
    get :sample
    expect(JSON.parse(response.body)[response]).to eq('Hello World')
  end
end

我收到此错误的原因是:async 只能由瘦服务器处理。普通 Rails Controller 中没有可用的瘦服务器。

所以尝试了 capybara :

  describe "GET /sample", type: feature do
    it "hello world" do
      visit sample_path

      expect(JSON.parse(page.body)['response']).to eq('Hello World')
    end
  end


  # In spec_helper.rb
  Capybara.server do |app, port|
    require 'rack/handler/thin'
    Rack::Handler::Thin.run(app, :Port => port)
  end

但我仍然遇到同样的错误。我相信这是因为 Thin 需要以线程模式启动;而 capybara 不会以这种方式启动它。

使用 throw :async 测试 Controller 操作的正确方法是什么?

当我使用常规浏览器访问该操作时,该操作确实有效。

最佳答案

为了测试使用 Thin 实现的异步 Ruby on Rails 操作,您需要使用 Thin 运行测试。否则它会失败,或者很脆弱——以防你尝试模仿。

所以让我们使用 Capybara 进行设置:

在 Gemfile 中:

gem 'thin'
gem 'capybara'
gem 'selenium-webdriver'

在spec/rails_helper.rb中:

require 'capybara/rails' 

Capybara.default_driver = :selenium

Capybara.server do |app, port|
  require 'rack/handler/thin'
  Rack::Handler::Thin.run(app, :Port => port)
end

这将 Capybara 驱动程序设置为 selenium,一个真正的浏览器。第二部分将 Capybara 服务器配置为 Thin。

测试应该这样写:

describe SampleController, :type => :feature do
  it "my test" do
    visit sample_path
    expect(page).to have_content('Hello World')
  end
end

这将使测试通过。

关于ruby-on-rails - 使用 throw :async? 测试 Rails Controller 操作的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26039452/

相关文章:

ruby-on-rails - Rails 5 集成测试失败,出现 NoMethodError : undefined method `[]=' for nil:NilClass when using Devise helper sign_in

ruby-on-rails - 在Rails 3中进行就地编辑

ruby-on-rails - 如何在 Rails 中为编辑页面生成到期链接

html - 如何在我的 Rails 应用程序中将网页另存为图像?

ruby-on-rails - Launchy 打开编辑器而不是浏览器

ruby - 将 JS 文件注入(inject) capybara chrome headless

ruby-on-rails - Rspec - 如何测试邮件程序是否使用了正确的模板

ruby-on-rails - 在每次使用 Spork 运行时强制重新加载 application_controller

rspec - capybara :无法找到 css

ruby-on-rails - 使用 capybara has_context 一次检查多行