Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save javascript variable to cucumber variable

I use Gherkin with Cucumber. But unfortunately I need to fetch some data from server with JavaScript.

Question: How to save JavaScript request result to cucumber variable to be able to reuse the result in next steps?

Code:

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
like image 933
VB_ Avatar asked May 08 '26 10:05

VB_


1 Answers

I did it this way:

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

So you see, it appends hidden input element to form element with stringified value of res. Then I wait for ajax to execute. And then I find it's value on page.

like image 98
Yevgeniy Anfilofyev Avatar answered May 10 '26 00:05

Yevgeniy Anfilofyev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!