如何在黄瓜测试期间运行后台作业?

时间:2015-03-12 21:05:38

标签: ruby-on-rails ruby cucumber

测试需要黄瓜背景作业的最佳方法是什么?我需要在测试运行时在后台运行DelayedJob和Sneakers工作人员。

3 个答案:

答案 0 :(得分:1)

您可以在后台运行任何应用程序:


    @pid = Process.spawn "C:/Apps/whatever.exe"
    Process.detach(@pid)

甚至在测试完成后杀死它:


    Process.kill('KILL', @pid) unless @pid.nil?

答案 1 :(得分:1)

您可以在features/step_definitions/whatever_steps.rb中创建自己的步骤定义(希望名字更好)

When /^I wait for background jobs to complete$/ do
  Delayed::Worker.new.work_off
end

可以针对您希望在该步骤中运行的任何其他脚本进行扩展。然后在测试中,它类似于:

Then I should see the text "..."
When I wait for background jobs to complete
And I refresh the page
Then I should see the text "..."

答案 2 :(得分:0)

如果有人有类似的问题,我最后写了这篇文章(感谢Square博客文章):

require "timeout"

class CucumberExternalWorker
  attr_accessor :worker_pid, :start_command

  def initialize(start_command)
    raise ArgumentError, "start_command was expected" if start_command.nil?

    self.start_command = start_command
  end

  def start
    puts "Trying to start #{start_command}..."
    self.worker_pid = fork do
      start_child
    end

    at_exit do
      stop_child
    end
  end

  private

  def start_child
    exec({ "RAILS_ENV" => Rails.env }, start_command)
  end

  def stop_child
    puts "Trying to stop #{start_command}, pid: #{worker_pid}"

    # send TERM and wait for exit
    Process.kill("TERM", worker_pid)

    begin
      Timeout.timeout(10) do
        Process.waitpid(worker_pid)
        puts "Process #{start_command} stopped successfully"
      end
    rescue Timeout::Error
      # Kill process if could not exit in 10 seconds
      puts "Sending KILL signal to #{start_command}, pid: #{worker_pid}"
      Process.kill("KILL", worker_pid)
    end
  end
end

这可以如下调用(将其添加到黄瓜的env.rb):

# start delayed job
$delayed_job_worker = CucumberExternalWorker.new("rake jobs:work")
$delayed_job_worker.start