How to get placeholder value using assert_selector in rails - ruby-on-rails

How do I get the placeholder value from an input bar using assert_selector in rails ?
<input placeholder="hello world" value="<%= params[:query] %>" required>
I want to check is placeholder has hello in it

While the answer by Lam Phan does answer the question, resorting to writing XPath queries when CSS has what you need isn't usually the best idea from a readability/understandability perspective.
CSS has a number of attribute selectors, the most useful for testing usually being
= matching
*= containing
^= begins with
~= whitespace separated matching
You can see the full set at https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors
In this case that means you could do any of
assert_selector('input[placeholder*="hello"]') # contains 'hello'
assert_selector('input[placeholder~="hello"]') # contains the word 'hello'
assert_selector('input[placeholder^="hello"]') # starts with 'hello'
Another option would be take advantage of the fact that the Capybara :field selector has a placeholder filter - https://github.com/teamcapybara/capybara/blob/master/lib/capybara/selector.rb#L34 - which takes a regex - so you could do
assert_field(placeholder: /hello/)
which is the same as
assert_selector(:field, placeholder: /hello/)

you could use xpath and verify that there's an input element whose's placeholder contains 'hello'
assert_selector(:xpath, './/input[contains(#placeholder,"hello")]')
if you want to check exactly an input with id
assert_selector(:xpath, './/input[#id="input_id"][contains(#placeholder,"hello")]')
im not sure there's a helper method that check regex something like ~= /.*hello.*/, if you want to do that, you still have another choice
placeholder = find('#input_id')['placeholder'] # or use :xpath
assert_match /.*hello.*/, placeholder

Related

How to html escape variables in Thymeleaf?

I would like to display several variables in a web page using Thymeleaf.
I have the code set as follows...
<span th:text="${foo.bar}" />
The problem is that when property foo.bar contains multiple spaces in a row, they are displayed as one (expected behaviour for HTML).
e.g. "hello world" => "hello world"
Is there a "Thymeleaf" way to HTML escape the value of the variable so that the value visually appears exactly as it should be?
I think the best way is to use HTML's way of accomplishing this: either using <pre> tags (<pre th:text="${foo.bar}" />), or else using the css white-space property and changing the style of your <span> tags that contain variables.
I guess you could also replace ' ' with (like this: <span th:text="${#strings.replace(foo.bar, ' ', ' ')}" />, but that would be my last option.

Testing for italics with Capybara

Could anyone suggest the best way to look for italics on a page with capybara. I have a feature test that searches for a specific piece of text within a page. This text is in italics and is also a different colour from everything else on the page. I thought looking for italics would be preferable to searching for a colour value but i am unsure how to do either.
<div class="text-control">
<p class="body">Test text is here and then<i>italics</i> are there</p>
</div>
The feature test is written as follows:
Then(/^the word should be highlighted in the example sentence$/) do
end
It sounds like just need to check that the sentence, the p element, contains the word, the i element. To do this you can do:
# Get the element containing the sentence
sentence_element = find('p.body')
# Check that the sentence includes the italics element with a specific text
expect(sentence_element).to have_css('i', text: 'italics')
Assert a text is present in the particular element, sounds reasonable... you can do that using the suggesting by Justin...
Test a text is in italic... that's not a test you want to add in this layer of testing or in any layer in fact...

Using Capybara determine whether a form field exists or not

I want to determine that an input field with id="foo" exists:
<input id="foo" ... />
And I also want to ensure that under certain conditions another input field with id="bar" does not exist.
Exists:
expect(page).to have_css('#bar')
Doesn't exist:
expect(page).to have_no_css('#bar')
Note: Don't use expect(page).to_not have_css, as that will wait for your element to appear.
An explanation of expect and negative forms like has_no_selector? and not has_selector? can be found in Capybara's Asynchronous JavaScript documentation.
To determine that a particular input field exists, use:
assert has_xpath?("//input[#id='foo']")
To determine that a particular input field does not exist, use one of:
assert has_no_xpath?("//input[#id='bar']")
refute has_xpath?("//input[#id='bar']")
Search for has_xpath in these Capybara node matcher docs.

Rails only escape certain sections of content

I'm looking to turn all words preceeded by a # (ie #stackoverflow) into a link that when clicked through will link to the search page with the word as a query.
I tried this recently and got the right HTML being returned, but because content is automatically escaped it showed as:
This is some content something
My question is: Is there any way to only apply html_safe to every part of the content except for these links?
If your tags are simple alphanumeric strings (i.e. nothing that needs to be HTML or URL encoded), then you could do something like this:
s = ERB::Util.html_escape(text_to_be_linkified).gsub(/#(\w+)/, '\1').html_safe
Then s.html_safe? will be true and <%= ... %> will pass the result through as-is. If you put this in a view helper, then you shouldn't need the ERB::Util. prefix on html_escape. If you do need to worry about URL or HTML encoding then you could modify the gsub replacement string appropriately.
For example:
> s = ERB::Util.html_escape('<pancakes & #things').gsub(/#(\w+)/, '\1').html_safe
> puts s.html_safe?
true
> puts s
<pancakes & things

Haml: Control whitespace around text

In my Rails template, I'd like to accomplish final HTML to this effect using HAML:
I will first link somewhere, then render this half of the sentence if a condition is met
The template that comes close:
I will first
= link_to 'link somewhere', 'http://example.com'
- if #condition
, then render this half of the sentence if a condition is met
You may, however, note that this produces a space between the link and the comma. Is there any practical way to avoid this whitespace? I know there's syntax to remove whitespace around tags, but can this same syntax be applied to just text? I really don't like the solution of extra markup to accomplish this.
A better way to do this has been introduced via Haml's helpers:
surround
= surround '(', ')' do
%a{:href => "food"} chicken
Produces:
(<a href='food'>chicken</a>)
succeed:
click
= succeed '.' do
%a{:href=>"thing"} here
Produces:
click
<a href='thing'>here</a>.
precede:
= precede '*' do
%span.small Not really
Produces:
*<span class='small'>Not really</span>
To answer the original question:
I will first
= succeed ',' do
= link_to 'link somewhere', 'http://example.com'
- if #condition
then render this half of the sentence if a condition is met
Produces:
I will first
link somewhere,
then render this half of the sentence if a condition is met
You can also do this using Haml's "trim whitespace" modifier. Inserting > after a Haml declaration will prevent whitespace from being added around it:
I will first
%a{:href => 'http://example.com'}> link somewhere
- if #condition
, then render this half of the sentence if a condition is met
produces:
I will first<a href='http://example.com'>link somewhere</a>, then render this half of the sentence if a condition is met
However, as you can see, the > modifier also strips the whitespace in front of the link, removing the desired space between the words and the link. I haven't figured a pretty way around this yet, except to add to the end of "I will first", like so:
I will first
%a{:href => 'http://example.com'}> link somewhere
- if #condition
, then render this half of the sentence if a condition is met
Which finally produces the desired output without lots of hard-to-read interpolation:
I will first <span>link somewhere</span>, then render this half of the sentence if a condition is met
Alright, here's the solution I'm settling on:
Helper
def one_line(&block)
haml_concat capture_haml(&block).gsub("\n", '').gsub('\\n', "\n")
end
View
I will first
- one_line do
= link_to 'link somewhere', 'http://example.com'
- if #condition
, then render this half of the sentence
\\n
if a condition is met
That way, whitespace is excluded by default, but I can still explicitly include it with a "\n" line. (It needs the double-backslash because otherwise HAML interprets it as an actual newline.) Let me know if there's a better option out there!
You can use the 'aligator syntax' of HAML
Whitespace Removal: > and <
and < give you more control over the whitespace near a tag. > will remove all whitespace surrounding a tag, while < will remove all whitespace immediately within a tag. You can think of them as alligators eating the whitespace: > faces out of the tag and eats the whitespace on the outside, and < faces into the tag and eats the whitespace on the inside. They’re placed at the end of a tag definition, after class, id, and attribute declarations but before / or =.
http://haml.info/docs/yardoc/file.REFERENCE.html#whitespace_removal__and_
Once approach I've taken to this sort of thing is to use string interpolation:
I will first #{link_to 'Link somewhere'}#{', then render this half of the sentence if a condition is met' if condition}
I don't like the look of the literal string in the interpolation, but I've used it with previously declared strings or dynamically generated strings before.
You can do this to keep the leading space:
%a{:href => 'http://example.com'}>= ' link somewhere'
The space is in the quotes.
Although not well documented, this is cleanly achieved using HAML whitespace preservation (>) combined with an ASCII space (& #32;), and not with helpers:
%a{:href=>'/home'}> Home link
,
%a{:href=>'/page'} Next link
This will produce what you want:
<a href='/home'>Anchor text</a>,
<a href='/page'>More text</a>
But I agree, HAML needs to come up with a better way of doing this, as it does add unnecessary ASCII characters to the page (but it's still more efficient than using helpers).
There's the angle bracket "whitespace munching" syntax, otherwise write a helper method for it.
I came across a similar problem and found this so I thought I would post another solution which doesn't require a helper method. Use Ruby interpolation #{} to wrap the link and if statements:
I will first
#{link_to 'link somewhere', 'http://example.com'}#{if true : ", then render this half of the sentence if a condition is met" end}
This works in 3.0.18, it may also work in earlier releases.
Yet another option that I've used in the past:
- if #condition
%span> , then some more text after the link.
You could also always do:
= link_to url_path do
= ["part_1", "part_2"].join(", ")
The solution that I got working is:
I will first
= link_to 'link somewhere', 'http://example.com'
- if #condition
= ", then render this half of the sentence if a condition is met"
You can use =, though = is used to output the result of Rails code, but here it will server the purpose.
The preserve function worked for me
.white-space-pre= preserve "TEXT"

Resources