【问题标题】:Rails double render error for multithreading多线程的Rails双重渲染错误
【发布时间】:2014-04-25 23:07:33
【问题描述】:

我想同时从不同的地方在rails中测试sign_in,所以我在rspec中使用了多线程:

context 'when multiple api calls made at same time' do
  it 'sign_in successfully' do
    request.env["devise.mapping"] = Devise.mappings[:user]
    threads = []
    10.times do
      threads << Thread.new do
        post :create, user: { email: user.email, password: user.password }
      end
    end

    threads.each do |t|
      t.join
    end
  end
end

上面的代码有双重渲染错误:

 AbstractController::DoubleRenderError:
 Render and/or redirect were called multiple times in this action. Please note that you  
 may only call render OR redirect, and at most once per action. Also note that neither 
 redirect nor render terminate execution of the action, so if you want to exit an action 
 after redirecting, you need to do something like "redirect_to(...) and return".

我的控制器代码:

def create
  resource = warden.authenticate!(:scope => resource_name)
  return sign_in_and_redirect(resource_name, resource)
end

def sign_in_and_redirect(resource_or_scope, resource=nil)
  scope = Devise::Mapping.find_scope!(resource_or_scope)
  resource ||= resource_or_scope
  sign_in(scope, resource) unless warden.user(scope) == resource

  if user_signed_in? && (cannot? :view, :my_app)
    sign_out current_user
    render :status => 401, :json => { :error =>"Access denied." }
  else
    render :json => current_user, :location => after_sign_in_path_for(resource)
  end
end

该规范适用于 1.time。知道为什么它抱怨多线程的双重渲染错误吗?谢谢。

【问题讨论】:

    标签: ruby-on-rails ruby multithreading rspec rendering


    【解决方案1】:

    post 测试方法不会使用整个 Rack 堆栈,它只是模拟出必要的东西并在控制器实例上调用该方法。对于这种全栈集成测试——你可能会想要像 Cucumber 这样的东西——它在 Web 服务器的单独线程中运行请求。 (并且您可能需要某种并行测试设置来确保一次有多个服务器线程。)

    也就是说 - 我认为您在这种情况下正在测试库和 Rails - 您在此处编写的任何代码都不会引入线程问题,因此除非您有理由相信 Devise 和/或 Rails 在这种情况下会失败您正在尝试在这里重新创建,我不确定是否真的需要进行测试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-21
      相关资源
      最近更新 更多