How do you refute the presence of an option with Capybara's has_select? - testing

Consider that you have a select list with just the following option:
<option>Second Fake Option</option>
And you'd like to assert that the select list does not contain an option with the text "Fake Option":
<option>Fake Option</option>
When one refutes this like so:
refute has_select?('list_id',
with_options: ['Fake Option'])
The test fails. It seems that Capybara is successfully partially matching the text Fake Option against the text Second Fake Option. Even further, the following also fails:
refute has_select?('select_id',
with_options: [''])
Yet the following passes:
refute has_select?('select_id',
with_options: ['BORK'])
The documentation for with_options: and options: describes the behavior regarding the list of options we're trying to match, but does not speak to this behavior of partially matching the text itself. Other questions here on SO refer to the same documented behavior... but don't address refuting or the matching of the options' text.
While I could assert the opposite behavior with options:, like this:
assert has_select?('select_id',
options: ['Second Fake Option'])
This can be a pain when you have a long select list and want to refute the presence of one particular option in the list.
How does one properly refute the presence of a specific option in a select list?

Partial text matching is the default behavior but can be overridden with the :exact option. Also rather than refuting a predicate, you should be calling refute_select -- the error messages will be much better
refute_select('select_id', with_options: ['Fake Option'], exact: true)
Note: this would also pass if there was no 'select_id' select element on the page, which may not be what you want. If you want to verify the select does exist but that it doesn't have a specific option then something like
select = find_field('select_id')
refute_selector(select, :option, 'Fake Option', exact: true)
may be what you want, which could also be done with matches as
select = find_select('select_id')
refute_matches_selector(select, :select, with_options['Fake Option'], exact: true)

Related

want yadcf filter multiselect options based on another filter value

I am using yadcf 0.9.3.
I have data similar to the following
race1,event1,otherfields
race1,event1,otherfields
race1,event2,otherfields
race1,event2,otherfields
race2,event3,otherfields
race2,event4,otherfields
I want to be able to select race (e.g., race1) with one filter, then have event filter multiselect show only appropriate events (in this case event1, event2). And when I select another race (e.g., race2) only those events are shown (in this case event3, event4)
I tried cumulative_filtering = true, but that doesn't work for my use case. First of all with cumulative_filtering = true, once I've selected race1, I can't change the selection to race2, also I have read other stackoverflow questions which noted that multiselect doesn't work well with cumulative_filtering because once the first options is chosen the others disappear.
This could work similar to datatables Editor dependent(), I suppose.
Is there any way to achieve this with the current or more recent yadcf? I reviewed 0.9.3.beta.26 (well master/latest, see https://github.com/vedmack/yadcf/blob/94a95338e697f972fa64bc79e4276fc35c8f3c40/src/jquery.dataTables.yadcf.js), and I am not sure if the new features would work (although it's possible something can be done with exRefreshColumnFilterWithDataProp -- note doc goes off the right side of the page when reviewing through github, so formatting could be improved).
If exRefreshColumnFilterWithDataProp should be used, is there a best practice to determine the values for one column (in my case events) given a filter in another (in my case races)?
UPDATE1 with codepen test case: https://codepen.io/louking/pen/VOrYjr

Concise Xpath to simulate finding an element regardless of page structure? (selenium)

If you're visually looking at a webpage and there is something clickable and unique on the page, you'll just click it. Without thinking about the page structure.
I'm interested to see what the most concise xpath is that could be constructed to simulate this in a versatile manner.
For example, target the "I'm feeling Lucky" button on the Google homepage:
//*[contains(#*, 'Lucky')]
The above works. But would fail in the element contained Lucky as inner text, or if the wrong case was specified. As such, our xpath needs to cater for any sensitivity and also look for the given string matching inner-text as well.
How could the above xpath be expressed in the most concise yet encompassing structure?
There is nothing thats very generic and executing such xpaths could be costly also at times.
"//*[contains(#*, 'Lucky')] | //*[contains(text(), 'Lucky')]"
Above is one xpath you can combine to get some results. You start specifying which nodes you don't to examine or ones which you want to examine
"//*[contains(#*, 'Lucky')] | //*[contains(text(), 'Lucky')][not(self::script|self::td)]"
And you can keep improving it
It's not possible to create a versatile XPath to accurately/reliability locate an element by text.
Why?
Because the text evaluated by an XPath is not necessary rendered in the page.
Because there's a hight chance to end-up with multiple matches since each ancestor also contains the expected text.
But mainly because there's too many rules/specific cases to consider.
But if I had to create one, then I'd start with this one:
"(html/body//*[not(self::script or self::style)][contains(concat(#value, normalize-space()), 'MyText')])[last()]"
Get all the descendants of the <body>
html/body//*
except <script> and <style>
[not(self::script or self::style)]
where the value attribute or normalize html contains 'MyText'
[contains(concat(#value, normalize-space()), 'MyText')]
then returns the last and deepest match
[last()]

Capybara, selecting 1st option from dropdown?

I've done a search and most of the related google results have returned just in general selecting an element from a dropdown. However the ID's in this case for the elements in the dropdown are dynamically generated unfortunately.
This is for a base test case, so I basically just need to select for example the first one. The text is also the same for the elements in the dropdown (not sure if that helps).
Is there such an example of this?
Im using cucumber with caybara(using selenium driver) integration
You can find the first option element and then use the select_option method to select it.
For example, if the select list has an id "select_id", you can do:
first('#select_id option').select_option
As #TomWalpole mentions, this will not wait for the element to appear. It would be safer to do one of the following:
first('#select_id option', minimum: 1).select_option
or
find('#select_id option:first-of-type').select_option
Alternatively you can get the first element text then select it by select function:
first_element = find("#id_of_dropdown > option:nth-child(1)").text
select(first_element, :from => "id_of_dropdown")
After two days of searching and reading, this article was amongst one of a few that was helpful. Hopefully, this can help someone else!
I created a few methods like so, excuse the naming..I changed it.
def some_dropdown(id, text)
dropdown = find(id).click
dropdown.first('option', text: text).select_option
end
def select_form
within 'content#id' do
some_dropdown('#id', text)
click_link_or_button 'Submit'
end
end
I also referenced this.
I've tried to select an option from a modal dropdown. After trying all listed methods, and many other from other threads - I totally gave up and instead of using clicks or select_option just used keyboard keys
find(:select, "funding").send_keys :enter, :down, :enter
In case it still complains - try:
find(:select, "funding", visible: false).send_keys :enter, :down, :enter
Worked like a charm, selecting first option from a dropdown.

Selenium Webdriver - using isDisplayed() in If statement is not working

I am creating a script that involved searching for a record and then updating the record. On the search screen, the user has the option of viewing advanced search options. To toggle showing or hiding advanced search is controlled by one button.
<a title="Searches" href="javascript:expandFilters()"><img border="0" align="absmiddle" alt="Advanced" src="****MASKED URL****"></a>
The only difference between the properties of the search button when it is showing or hiding the advanced search is the img src:
When advanced search is hidden the IMG src ends with "/Styles/_Images/advanced_button.jpg", when advanced search is visible, the IMG src ends with "/Styles/_Images/basic_button.png"
When I open the page, sometimes the Advanced search options are showing, sometimes they aren't. The value that I want to search on appears in the Advanced section, so for my script to work I have added an IF statement.
<input type="text" value="" maxlength="30" size="30" name="guiSystemID">
The IF statement looks for the fields that I need to enter data into, and if the field does not exist then that would indicate that the Advanced options are not visible I need to click on the button to expand the search option.
I created the following IF statement.
if (!driver.findElement(By.name("guiSystemID")).isDisplayed()) {
driver.findElement(By.cssSelector("img[alt='Advanced']")).click();
}
When I run the script and the Advanced search is expanded then the script runs successfully. However, when I run the script and the Advanced search is not expanded, the script fails, advising me that it could not find the object "guiSystemID". This is frustrating because if it can't find it then I want the script to continue, entering into the True path of the IF statement.
Has anyone got any suggestions about how else I could assess if the field is appearing without having the script fail because it can't find the field.
Thanks in advance
Simon
I might be late in answering this, but it might help someone else looking for the same.
I recently faced a similar problem while working with isDisplayed(). My code was something like this
if(driver.findElement(By.xpath(noRecordId)).isDisplayed() )
{
/**Do this*/
}
else
{
/**Do this*/
}
This code works pretty well when the element that isDisplayed is trying to find is present. But when the element is absent, it continues looking for that and hence throws an exception "NosuchElementFound". So there was no way that I could test the else part.
I figured out a way to work with this(Surround the {if, else} with try and catch block, say something like this.
public void deleteSubVar() throws Exception
{
try
{
if(driver.findElement(By.xpath(noRecordId)).isDisplayed() )
{
/**when the element is found do this*/
}
}
catch(Exception e)
{
/**include the else part here*/
}
}
Hope this helps :)
I've had mixed results with .isDisplayed() in the past. Since there are various methods to hide an element on the DOM, I think it boils down to a flexibility issue with isDisplayed(). I tend to come up with my own solutions to this. I'll share a couple things I do, then make a recommendation for your scenario.
Unless I have something very specific, I tend to use a wrapper method that performs a number of checks for visibility. Here's the concept, I'll leave the actual implementation approach to you. For general examples here, just assume "locator" is your chosen method of location (CSS, XPath, Name, ID, etc).
The first, and easiest check to make is to see if the element is even present on the DOM. If it's not present, it certainly isn't visible.
boolean isPresent = driver.findElements(locator).size() > 0;
Then, if that returns true, I'll check the dimensions of the element:
Dimension d = driver.findElement(locator).getSize();
boolean isVisible = (d.getHeight() > 0 && d.getWidth() > 0);
Now, dimensions, at times, can return a false positive if the element does in fact have height and width greater than zero, but, for example, another element covers the target element, making it appear hidden on the page (at least, I've encountered this a few times in the past). So, as a final check (if the dimension check returns true), I look at the style attribute of the element (if one has been defined) and set the value of a boolean accordingly:
String elementStyle = driver.findElement(locator).getAttribute("style");
boolean isVisible = !(elementStyle.equals("display: none;") || elementStyle.equals("visibility: hidden;"));
These work for a majority of element visibility scenarios I encounter, but there are times where your front end dev does something different that needs to be handled on it's own.
An easy scenario is when there's a CSS class that defines element visibility. It could be named anything, so let's assume "hidden" to be what we need to look for. In this case, a simple check of the 'class' attribute should yield suitable results (if any of the above approaches fail to do so):
boolean isHidden = driver.findElement(locator).getAttribute("class").contains("hidden");
Now, for your particular situation, based on the information you've given above, I'd recommend setting a boolean value based on evaluation of the "src" attribute. This would be a similar approach to the CSS class check just above, but used in a slightly different context, since we know exactly what attribute changes between the two states. Note that this would only work in this fashion if there are two states of the element (Advanced and Basic, as you've noted). If there are more states, I'd look into setting an enum value or something of the like. So, assuming the element represents either Advanced or Basic:
boolean isAdvanced = driver.findElement(locator).getAttribute("src").contains("advanced_button.jpg");
From any of these approaches, once you have your boolean value, you can begin your if/then logic accordingly.
My apologies for being long winded with this, but hopefully it helps get you on the right path.
Use of Try Catch defies the very purpose of isdisplayed() used as If condition, one can write below code without using "if"
try{
driver.findElement(By.xpath(noRecordId)).isDisplayed();
//Put then statements here
}
Catch(Exception e)
{//put else statement here.}

selenium (phpunit) click on drop down link

I want be able click on link from drop down using selenium with phpunit. I don't have any idea how make it happens, can anyone show me example or relevant tutorial, post or anything that can help me figure out.
when I try click on the element without put mouse over the drop down I got this error:
Element is not currently visible and so may not be interact with command ....
Thanks.
EDIT:
when I said "drop down" I don't mean regular select. it more like popup
you can see the example here:
http://investing.com
look how they build the menu I want be able click on 'Technical' -> 'Fibonacci Calculator' for example.
Check this post out:
Selenium: How to select an option from a select menu?
You can find more info about this here
select(selectLocator, optionLocator)
Arguments:
selectLocator - an element locator identifying a drop-down menu
optionLocator - an option locator (a label by default)
Select an option from a drop-down using an option locator.
Option locators provide different ways of specifying options of an HTML Select element (e.g. for selecting a specific option, or for asserting that the selected option satisfies a specification). There are several forms of Select Option Locator.
label=labelPattern: matches options based on their labels, i.e. the visible text. (This is the default.)
label=regexp:^[Oo]ther
value=valuePattern: matches options based on their values.
value=other
id=id: matches options based on their ids.
id=option1
index=index: matches an option based on its index (offset from zero).
index=2
If no option locator prefix is provided, the default behaviour is to match on label.
Credits go to Dave Hunt
What I use:
$search13 = $this->webDriver->findElement(WebDriverBy::id('id_of_dropdown_field'));
$search13->click(); // Clicking on the dropdownfield
$this->webDriver->getKeyboard()->pressKey('ARROW_DOWN'); // Will go down in your dropdown selection )
sleep(1);
$this->webDriver->getKeyboard()->pressKey('ENTER'); // Enter for submitting your selection
EDIT:
http://www.anitpatel.net/2012/02/25/selenium-webdriver-how-to-click-on-a-hidden-link-or-menu/
This one explains it in java but basically what he does is a mouse over/hover and wait.
Then he clicks on the element.
I'm not a java genius but it's an example how to work with it.
You can use the:
string mouseOver(string $locator)
This simulates a user hovering a mouse over the specified element.
http://docs.tadiavo.com/phpunit/www.phpunit.de/pocket_guide/3.1/en/selenium.html
Check if the element is visible using the xpath of the required option value.
$this->isElementPresent($xpath);
$this->click($xpath);
If it is true, then click() method selects the specified option.