Using Cucumber, Webrat and Selenium to test ajax form field validations
September 4th, 2009 • Cucumber, Internet, JavaScript, Merb, Ruby, Webrat, programming
I have an app that fires an ajax request on a form field to validate its contents when I take focus off the field.
I am also using Cucumber, Webrat and Selenium for my integration tests.
I needed my integration tests to test the Ajax responses and the tests weren’t receiving a response from the Ajax requests.
The Problem
I found that by simply completing the web form, the ajax request was not being fired and my test was therefore failing when i checked for the existance of the Ajax response. It soon became clear that selenium doesn’t really interact with the form in the sense of selecting fields and entering values; It simply enters values. As such, the Ajax request was not firing and my test was failing.
The Solution
The solution is Selenium’s fireEvent method, which you can pass a form field id and the blur method:
selenium_session.fireEvent(”field”, “blur”);
In Webrat, this is ever simpler:
fire_event(”field”,”blur”)
On using this in a Cucumber step, the ajax is fired as the blur command tells the browser to take focus off the field.
Lovely!
Andy, as the creator of Selenium, I have to apologize for the behavior you found in Selenium.
But thanks for finding the work around! Selenium’s goal is to test web apps just as a user would. But since it was implemented in JavaScript, we cut some corners. We’re fixing this, though, in Selenium 2.0 — we’ll be using Native OS mouse and keyboard Events to interact with elements on a web page, so there won’t be any need for event fackery behind the scenes. (Though we’ll still leave fireEvent in place for those hard-to-predict edge cases that’ll still need the fackery.)