如何在涉及 asynchronous/parallel 操作的 Rails 方法上测试 Ruby?

How to test Ruby on Rails methods that involve asynchronous/parallel operations?

我有一个创建记录并等待它在循环中接收输入的方法,该循环发生直到记录的内容满足检查要求。

在正常使用中,该方法创建的记录在创建后显示在页面上的表单中。提交表单更新记录,导致循环退出和处理记录新输入数据的方法。

我如何为此编写测试?我不关心精确模拟用户输入和所有需要的东西;我只想能够修改记录 - 通常由单独的进程完成的任务(来自表单提交的更新)。

rails 模型中的示例代码:

def self.create_and_wait_on_record(msg)
  rec = create(question: msg)

  # At this point a web page detects this record and displays it in a form

  # Loop until some field on rec has received input (normally via form submission)
  until rec.filled_in?  
    sleep 1.second
    rec.reload
  end

  # Processing rec follows...
end

将测试分成两部分。

测试流程直到您等待输入。

然后从提供输入的那一刻开始测试流程。您要跳过的只是表单数据的提交 - 在我看来您不需要测试它。

编辑:在下面澄清您的问题。

我将重新定义 self.create_and_wait_on_record(msg) 以按如下方式工作:

def self.create_and_wait_on_record(msg)
  rec = create(question: msg)

  wait_and_process(rec)     
end

我将进行一项测试来验证 create_and_wait_on_record 创建记录并调用 wait_and_process:

it 'Creates the record and continues processing when capable' do 
  subject.should_receive(:wait_and_process).with(stub_rec)
  subject.create_and_wait_on_record(mock_msg)
end

还有一个继续这个过程的人

it 'Processes a record once it has been created and has had the requisite data populated' do 
   subject.stub(:create).and_return(mock_created_record)
   subject.create_and_wait_on_record(mock_msg)
end

那么您只需要确保为测试用例设置了输入,这样 #filled_in? 就不会永久循环。