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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With