简体   繁体   中英

Rails 4 - assert_select not working with element updated by javascript

I have a span element that is blank by default and updated when the page is loaded by javascript. This works great - however assert_select seems only able to get the initial HTML - BEFORE the page is finished loading. Is this the expected behavior? What am I doing wrong?

span element in a scaffold generated _form.html.erb:

...
<span id="confirm_loaded"></span>
...

---- In a .js file in app/assets/javascripts:

$(function(){
  $("#confirm_loaded").html("test");
});

---- When I load the page -- the page is updated via javascript and all is well.

However, in an integration test - this line:

assert_select "span#confirm_loaded", {text: "test"}

fails with the error:

<test> expected but was
<>..
Expected 0 to be >= 1.

which appears to confirm that the test isn't seeing the updated HTML element set by javascript (perhaps it's running before the page is fully loaded?)

A quick change to the page, remove the javascript and hardcode the HTML:

...
<span id="confirm_loaded">test</span>
...

And now the test passes (the assert_select is able to get the value and we're golden).

Is assert_select only able to get the initial value of HTML tags? Why is the assert_select not getting values updated by javascript as the page loads?

Thanks for your help.

Yes , you said right in you question. assert_select selects elements and makes equality tests on @response(@response.body) object. That's the actual response returned form server, so at that time no javascript code has executed so you get span with empty text. As scripts runs in your browser.

Thinking through this a bit, it could simply be the case that the command line tests are getting the response from the server and offering it up for parsing / verification.

This would have two important aspects:

  1. Scripts & client-side code would not be executed
  2. Enter on to the scene - testing frameworks that offer up browser interfaces, etc - so that client-side code gets rendered

Seems like this is the case - but - I'll leave the question open in case I'm missing something.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM