Refactor Massive Cucumber Step Definition - webdriver

My team is currently taking our old UI acceptance test scripts and automating them. To do this we are using Jruby, Cucumber and Watir-Webdriver. So far the automation process has been going pretty well. The only problem we have is that our step definitions are starting to get a bit out of hand.
For example, in most of our scenarios is a section like this:
Given I press the SEARCH_BUTTON
Then I should land on the SEARCH_PAGE
and the step definitions look like this:
Given(/I press the (.*)$/) do |buttonName|
if buttonName == 'SEARCH_BUTTON'
eval "$browser.#{$DataHash['home']['searchButton']}.when_present.click"
elsif buttonName == 'LOGIN_BUTTON'
eval "$b.#{$DataHash['loginPage']['loginButton']}.click"
elsif buttonName == 'HOME_BUTTON'
eval "$b.#{$DataHash['mainPage']['HomeButton']}.click"
elsif buttonName == 'ADD_PRODUCT_BUTTON'
#This if else ladder goes on like this for another 300+ lines
...
end
end
The $DataHash variable refers to config.yml, which uses a hash to store all of the different web elements we are using.
config.yml
home:
searchButton: "link(:id => 'searchBtn')"
searchTypeSelectBox: "select_list(:name => 'matchType')"
searchResetButton: "button(:id => 'resetSearch')"
#rest of the elements on the home page...
loginPage:
loginButton: "link(:id => 'login')"
#rest of the elements on the login page...
....
So $browser.$DataHash['home']['searchButton'].when_present.click is equivalent to $browser.link(:id => 'searchBtn').when_present.click
We are using this basic step definition for every button that a user could click, and at this point this one step definition is something like 300+ lines of code. Most of which are single lines like above. Our other step definitions have the same sort of problem. Are there any good ways of refactoring our step definitions to make them less bloated, or at least easier to search through, without making the actual steps any less re-useable?
Initially we thought we could have the same step definition in multiple files based on which page was being tested. So in searchDefinitions.rb there would be a step definition for Given(/I press the (.*)$/) do |buttonName| which only had the different buttons found on the search page. Then in homeDefinitions.rb would be the same step definition but only with code for the home page buttons. Basically breaking up the if-else ladder across multiple files. Of course, Cucumber doesn't allow the same step definition in multiple files so now we're at a bit of a loss.

As you mentioned you can reuse steps see Reuse Cucumber steps. But I personally found it pretty complicated when I tried to do it. So, from my side I suggest you to implement Page Object pattern. The idea is that you describe your pages or even some modules like separate entities which provides you with ability to interact with them. For understanding concept see here. And here you can find some example. Assuming this your step definition would like
Given(/I press the (.*)$/) do |buttonName|
#my_home_page.click_search_button
...
end
end
Where click_search_button method encapsulates your 'ladder' logic to press login button if search button is not present yet.
Hopefully it makes sense for you.

Supposing that the minor differences in the eval lines you show don't matter, extract the hash values that vary into a constant
BUTTON_KEYS = {
'search' => %w(home searchButton),
'login' => %w(loginPage loginButton)
# ...
}
and use it in your step definition:
Given(/I press the (.*) button$/) do |button_name|
keys = BUTTON_KEYS['button_name']
eval "$browser.#{$DataHash['#{keys[0]}']['#{keys[1]}']}.when_present.click"
end
Now you have half as many lines of code and less duplication.
I changed the step regexp to include "button", to remove that duplication from the button names, and the button names to be lowercase, as in normal English. Whether or not you're showing your feature files to non-programmers, Cucumber step names should read like natural language so that you can think about product requirements and not implementation details when you're reading them.
Alternative suggestion, valid if the two levels of keys in the the YAML are not really needed:
You could restructure the YAML like so
search button: "link(:id => 'searchBtn')"
search type select box: "select_list(:name => 'matchType')"
search reset button: "button(:id => 'resetSearch')"
# rest of the elements on the home page...
login button: "link(:id => 'login')"
# rest of the elements on the login page...
# ...
Then you wouldn't need the hash at all, and your step could just be
Given(/I press the (.*)$/) do |element_name|
eval "$browser.#{$DataHash['#{element_name}']}.when_present.click"
end
Or you could convert the YAML entirely into a hash (representing the method as a string and calling it with .send), which would prevent you from making some syntax errors.

Related

Cypress, page content and variables

Right or wrong: In Cypress, its impossible to read a value on page X, then keep this value and compare it to a value on page Y.
I can read a value from the page and log it:
cy.get('[data-e2e-selector=whatever]').then(elm => cy.log('Value from page X : ' + elm))
or, for instance, the number of elements with similar or partially matchin selectors:
cy.get('[data-e2e-selector=^whatever]').then(elm => cy.log('Number of elements like this on page X: ' + elm.length))
Hoever, I cannot create a variable of this, because of the asynchronous way Cypress runs. Right? Any value created to just be blank.
Nor can I pass the value read to a method, which in turn compares it to the value on the next page:
compareToValueOnNextPage(cy.get('[data-e2e-selector=^whatever]').then(elm => elm.length));
compareToValueOnNextPage(value: number) { // NB: Not sure if it's a number or string yet...
cy.get('[data-e2e-selector=^whateverNextPage]').then(elm => elm.length).should('have.length', 4)
}
Basically, if I want to compare values, the either have to be on the same page, or they need to be hard-coded. This is a huge limitation when actually end-to-end testing some applications. Very often, a value is created on page X, based on input which should in many cases ba random, thus creating a dynamic value in the test. Then, on page Y, that same value is fetch (from the backend) or shown in some other way, in a Summary etc. And, naturally, I want to compare the value shown on page X to the one shown on page Y/Summary. But this is not possible, due to the very unit-testing thinking that seems to be the foundation for Cypress.
Or am I missing something here? Are there ways around this that aren't ugly/smelly? I think it's possible to store the value on page X in a file, then read that file on page Y. However, Cypress seems to only have one option when reading the file, and that's reading the whole file and looking for a match. So that file would be a mess. Or I'd need several files.
I realize this is kind of trying to impose non-functional ways on a quite functional and asynchroeous technology. However, if it's not possible to "keep" a value and use it later, it's very limiting when it comes to end-to-end testing (even though it's not when the testing is unit-based on frontend components).
UPDATE:
As per Kerrry's suggestion in the answer below:
cy.get('[data-e2e-selector=dellan-accordion]')
.then(elm => cy.wrap(elm.length).as("myVariableName"));
-GO TO NEXT PAGE-
cy.get('[data-e2e-selector=betalingsplan-dellan]')
.then(elm => elm.length)
.should('have.length', myVariableName)
This yeilds "expected 4 to have property 'length'.
This means, obviously, that I cannot get the length of the length.
So I replace 'have.length' with 'eq':
cy.get('[data-e2e-selector=betalingsplan-dellan]')
.then(elm => elm.length)
.should('have.length', myVariableName)
And I get the following error:
expected 4 to equal 0
So, it seems that the first variable - myVariable - is gone after the first cy.get().
If I do everything inside one get (have another get inside that, where I go to the next page AND get the count of the elements), then it works. But the way Kerry shows it, it would be much more flexible. But, alas, the above error.
As jonrsharpe mentioned in the comments, please read the Cypress document on variables and aliases thoroughly. This is a core concept of Cypress, and it will give you a solid understanding of how to implement variables and carry the values between test steps.
The reader's digest example of what you how you can achieve is this:
cy.get('[data-e2e-selector=^whatever]')
.then(elm => cy.wrap(elm.length).as("myVariableName"));
What this is doing is cy.wrap will yield the value from elm.length in a Cypress command chain, which then allows you to assign it to an alias "myVariableName".
In your following test step where you want to compare the value on a separate page, you would then access the alias' value in one of two ways:
Using this.
cy.get('[data-e2e-selector=^whateverNextPage]')
.then(elm => elm.length)
.should('have.length', this.myVariableName)
OR
via cy.get()
cy.get("#myVariableName").then(function(variableValue){
cy.get('[data-e2e-selector=^whateverNextPage]')
.then(elm => elm.length)
.should('have.length', variableValue)
})

Is it possible to show all options in Tokenize2?

Tokenize2 is a javacsript lib to select multiple options.
It provides a very neat UI to start writing and then get a list of options to select from. Selected options will show up as "tags" that can be removed with "x" link.
So far all is fine. But Right now you need to know what your looking for and start write at least one character to see matching alternatives.
In my scenario there are very few alternatives and they are not known to the user. I would like to show ALL options when the user clicks the input box. There is a configuration option named searchMinLength but it is already set to 0.
Is there a workaround that can be used? Maybe like triggering load and dropdown manually?
I know there are a lot of similar alternatives but I picked Tokenize2 because:
It looks clean and nice
It works in mobile browsers
I don't know if there is an "official" approach, but after some investigation I have found an acceptable workaround.
After downloading the Tokenizer2 sourceode I found the following line that triggered my attention:
if(this.input.val().length > 0){
this.trigger('tokenize:search', [this.input.val()]);
}
My interpretation is that the internal search command is not triggered unless the user input has at least one character. This line in sourcecode could easily be modified. I have filed a suggestion for this here: https://github.com/zellerda/Tokenize2/issues/26
My current workaround is to add an event listener for the select event and there trigger the internal search command. That works fine for my scenario and does not force a source code rewrite.
$("#my-dropdown").on("tokenize:select", function (e: Event, routedEvent: boolean) {
$("#my-dropdown").trigger('tokenize:search', "");
});
Tokenize2
This link worked for me GitHub
$('.tokenize-sample-demo1').on('tokenize:select', function(container){
$(this).tokenize2().trigger('tokenize:search', [$(this).tokenize2().input.val()]);
});

mvcgrid.net unable to use toolbar

I'm working on a website with a feature that can sort users.
I'm using mvcgrid.net libs but I can't figure it out. the toolbar doesn't work.
I used most of the basic source codes from mvcgrid.net but when i press something in the search bar it doesn't work or the items per page selection.
If you have specific code to take a look at, please post. Otherwise, here are a few things you can check:
(1) Be sure you've applied the mvcgrid data attributes needed. For example, for a search field you might have these attributes:
<input
type="search"
data-mvcgrid-apply-additional="change"
data-mvcgrid-type="additionalQueryOption"
data-mvcgrid-option="search"
data-mvcgrid-name="ContactGrid">
(2) Be sure the value you chose for mvcgrid-option (in this example, "search") is then added when you configure the grid. For example:
MVCGridDefinitionTable.Add("ContactGrid", new MVCGridBuilder<ContactViewModel>(defaults)
.WithAdditionalQueryOptionNames("Search")
...
(3) You then need to read the attribute (again in the grid config) in your .WithRetrieveDataMethod()
string search = options.GetAdditionalQueryOptionString("search");
I've forgotten step 2 in the past -- that's generally what has tripped me up.

Kibana (Elasticsearch) dev environment

I want to embed one my specific chart in dahsboard of kibana. For that I need inject my JS into Kibana source. I have followed by instructions https://github.com/elastic/kibana/blob/master/CONTRIBUTING.md to provide test environment, but I have obtained an error after "./kibana --dev"
let _ = require('lodash');
^^^
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
SyntaxError: Unexpected strict mode reserved word
at Module._compile (module.js:429:25)
at Object..js (module.js:459:10)
at Module.load (module.js:348:32)
at Function._load (module.js:308:12)
at Array.0 (module.js:479:10)
at EventEmitter._tickCallback (node.js:192:41)
Can anybody help me with start environment, or advice. Probably, I am moving by wrong way...my general goal (inject my JS code into Kibana) can be reached by another approach.
Thanks
I have reached my general goal, and if it is right - I place here my approach. (also, as an answer for above question)
When I was seeking ways how to implement what I want (my own custom metrics in dashboard....only as training and for personal "sport interest" sake) - I had chosen next way.
First of all - you need pay attention on index.js, not small one but huge file (more than 5MB), it predominantly contains angularJS terms.
My steps was:
I put into HTML empty container for my metrics
<div class="metric_container"></div>.
HTML defines in index.js as
define('text!plugins/dashboard/index.html',[],function () { return '<div dashboard-app class="app-container dashboard-container">\n .....
you can try to search ctrl+F it over the index.js
I found variable with JSON data for charts (esResp)
I found watcher on changing it $scope.$watch('esResp', prereq(function (resp, pre Resp) {....
Put in the body of watcher my_function () call.
finished my_function() call, that contains completing HTML metric sample with renewed figures (from esResp JSON) and putting it into
metric_container
so, I can develop my own metrics, charts, and it will be renew, but ONLY based on information provided in charts.
So, If you need smth - you need firstly create appropriate chart because of data set for you own calculations and further visualization.
Something So.
I am sure, probably there is best way, but my was.
I have created a number of visualizations for Kibana 4.4.1, and once you have the right baseline, it is no big deal.
I encourage you to take a look at any of my sources, in order to know what has to be done (http://github.com/JuanCarniglia).
There are some basic files you need to have, and you have them, you just put them on the src/plugins directory, and restart kibana. If everything is fine, you get a new visualization on the list.
If you encounter any problems or need a more detailed description, send me a message or post it here and I'll try to explain with more detail.

Nested REST Routing

Simple situation: I have a server with thousands of pictures on it. I want to create a restful business layer which will allow me to add tags (categories) to each picture. That's simple. I also want to get lists of pictures that match a single tag. That's simple too. But now I also want to create a method that accepts a list of tags and which will return only pictures that match all these tags. That's a bit more complex, but I can still do that.
The problem is this, however. Say, my rest service is at pictures.example.com, I want to be able to make the following calls:
pictures.example.com/Image/{ID} - Should return a specific image
pictures.example.com/Images - Should return a list of image IDs.
pictures.example.com/Images/{TAG} - Should return a list of image IDs with this tag.
pictures.example.com/Images/{TAG}/{TAG} - Should return a list of image IDs with these tags.
pictures.example.com/Images/{TAG}/{TAG}/{TAG} - Should return a list of image IDs with these tags.
pictures.example.com/Images/{TAG}/{TAG}/{TAG}/{TAG}/{TAG} - Should return a list of image IDs with these tags.
etcetera...
So, how do I set up a RESTful web service projects that will allow me to nest tags like this and still be able to read them all? Without any limitations for the number of tags, although the URL length would be a limit. I might want to have up to 30 tags in a selection and I don't want to set up 30 different routing thingies to get it to work. I want one routing thingie that could technically allow unlimited tags.
Yes, I know there could be other ways to send such a list back and forth. Better even, but I want to know if this is possible. And if it's easy to create. So the URL cannot be different from above examples.
Must be simple, I think. Just can't come up with a good solution...
The URL structure you choose should be based on whatever is easy to implement with your web framework. I would expect something like:
http://pictures.example.com/images?tags=tag1,tag2,tag3,tag4
Is going to be much easier to handle on the server, and I can see no advantage to the path segment approach that you are having trouble with.
I assume you can figure out how to actually write the SQL or filesystem query to filter by multiple tags. In CherryPy, for example, hooking that up to a URL is as simple as:
class Images:
#cherrypy.tools.json_out()
def index(self):
return [cherrypy.url("/images/" + x.id)
for x in mylib.images()]
index.exposed = True
#cherrypy.tools.json_out()
def default(self, *tags):
return [cherrypy.url("/images/" + x.id)
for x in mylib.images(*tags)]
default.exposed = True
...where the *tags argument is a tuple of all the /{TAG} path segments the client sends. Other web frameworks will have similar options.

Resources