我将黄瓜和黄瓜一起使用。但不幸的是,我需要使用JavaScript从服务器中获取一些数据。

问题:如何将JavaScript请求结果保存到Cucumber变量中以便在以后的步骤中可以重用结果?

码:

Then(/^I load all stuff$/) do
  script = "(function  run(){
    var url = 'localhost:8o8o/getStuff';
    $.ajax({url: url}).then(function(res) {
      //PROBLEM: how to save 'res' variable to Ruby variable?
    });
  })()".gsub(/[\t\r\n]/, '');
  @browser.execute_script(script)
end

最佳答案

我这样做是这样的:

script = "$.ajax({url: '...'}).then(function(res){
    $('<input>').attr({
        type: 'hidden',
        id: 'foo',
        name: 'bar',
        value: JSON.stringify(res)
    }).appendTo('form');
});"
page.evaluate_script(script)
wait_for_ajax
res = page.find('#foo', visible: false).value


如此一来,它会将隐藏的输入元素附加到字符串化值为res的表单元素上。然后,我等待ajax执行。然后,我发现它在页面上很有价值。

关于javascript - 将javascript变量保存到 cucumber 变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28068404/

10-12 00:07
查看更多