Rails双重渲染错误多线程

时间:2014-04-25 23:07:34

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

我想同时在不同地方的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。知道为什么它抱怨多线程的双重渲染错误?感谢。

1 个答案:

答案 0 :(得分:0)

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

那就是说 - 我认为你在这种情况下测试库和rails - 你在这里编写的代码都不会引入线程问题,所以除非你有理由相信Devise和or Rails在这种情况下会失败你试图在这里重新创建,我不确定是否真的需要测试。