(Rails) Assert_Select's Annoying Warnings - ruby-on-rails

Does anyone know how to make assert_select not output all those nasty html warnings during a rake test? You know, like this stuff:
.ignoring attempt to close body with div
opened at byte 1036, line 5
closed at byte 5342, line 42
attributes at open: {"class"=>"inner02"}
text around open: "</script>\r\t</head>\r\t<body class=\"inner02"
text around close: "\t</div>\r\t\t\t</div>\r\t\t</div>\r\t</body>\r</ht"
Thanks

It's rather that your code is generating invalid HTML. I suggest running it through a validator and fixing all the validation errors.

You can find out which test ran into the problem by using the TESTOPTS v flag:
(bundle exec) rake test TESTOPTS="-v"
This will give:
test: Request the homepage should have a node list. (PresentControllerTest): .
test: Request the homepage should have the correct title. (PresentControllerTest): ignoring attempt to close div with body
opened at byte 4378, line 89
closed at byte 17745, line 393
attributes at open: {"class"=>"colleft"}
text around open: "class=\"colmid\"> \n\t\t\t<div class=\"colleft\""
text around close: "x2.js\" ></script>\n </body>\n</html>\n\n"
ignoring attempt to close div with html
opened at byte 4378, line 89
closed at byte 17753, line 394
attributes at open: {"class"=>"colleft"}
text around open: "class=\"colmid\"> \n\t\t\t<div class=\"colleft\""
text around close: "</script>\n </body>\n</html>\n\n"
.
test: Request the homepage should not set the flash. (PresentControllerTest): .
test: Request the homepage should respond with 200. (PresentControllerTest): .

Rails's HTML scanner expects XHTML, if you're using HTML4 where tags don't have explicit closing tags, you may get this warning... doesn't look like solved issue
http://dev.rubyonrails.org/ticket/1937
http://gilesbowkett.blogspot.com/2009/10/ignoring-attempt-to-close-foo-with-bar.html

What I'd want is to know where the warning is coming from. The fact it doesn't specify the test or the controller/action which generates the invalid HTML is the big problem for me.

I had some problems after an update to rails 3.0.9 and HAML 3.1.2
What I did was silence those ugly outputs with the following code in *test_helper.rb*
# Wrap up the method assert_select because after updating to Rails 3.0.9 and HAML 3.1.2,
# I don't know why but it was raising warnings like this:
# ignoring attempt to close section with body
# opened at byte 6157, line 128
# closed at byte 16614, line 391
# attributes at open: {"class"=>"left-column"}
# text around open: "->\n\n\n</span>\n</div>\n<section class='left"
# text around close: "'1'>\n</noscript>\n</body>\n</html>\n"
# But the HTML seems to be valid (in this aspects) using a HTML validator.
ActionDispatch::Assertions::SelectorAssertions.class_eval do
alias_method :assert_select_original, :assert_select
def assert_select(*args, &block)
original_verbosity = $-v # store original output value
$-v = nil # set to nil
assert_select_original(*args, &block)
$-v = original_verbosity # and restore after execute assert_select
end
end
Anyway, I don't recommend using a solution like this. Use only if you are in hurry, and give it a good comment to explain other developers why is that estrange piece of code there.

For me, the cause was valid but poorly formed HAML.
This is what I had:
%ul
%li
= link_to "Help", help_url
- if current_user
%li
= link_to "Users", users_url
= link_to "Logout", logout_url
- else
= link_to "Login", login_url
This is what is correct for what I'd wanted to do:
%ul
%li
= link_to "Help", help_url
%li
- if current_user
= link_to "Users", users_url
= link_to "Logout", logout_url
- else
= link_to "Login", login_url
The best way to track this down is to look very carefully at the "text around open" and "text around close" and try to track down where in your template the open occurs.

Even if you do rake test TESTOPTS="-v" and the error appears to be coming from your view templates, DON'T forget to check the application layout html. This happened to me and it took a few minutes longer than I'd like to admit going back and forth between a couple index.html.erb files before I finally figured it out. Same goes for any rendered partials.

Related

Direct Printing in Rails app using system commands

I have a method in which I'm trying to print a pdf directly from! As you can see here
I have to use system(lpr) command.This solutions works fine but in ubuntu not in windows or any other OSs. Do you know how to do it in windows ?
and this is my method:
def general_receipt_export
if params[:official_id].present?
#ids = params[:official_id].split(',')
#officials = Official.find(#ids)
pdf = render_to_string pdf: "#{#ids.map(&:inspect).join(',').to_s + '_receipt.pdf'}", :template => 'officials/general_receipt_export.html.erb', encoding: 'utf8',orientation: 'Landscape',page_size: 'A4'
render layout: false
save_path = Rails.root.join('public','pdfs', "#{#ids.map(&:inspect).join(',').to_s + '_receipt.pdf'}")
File.open(save_path, 'wb') do |file|
file << pdf
end
system("lpr", "public/pdfs/#{#ids.map(&:inspect).join(',').to_s + '_receipt.pdf'}")
else
render json:{messege: 'No letter to export'},status: 404
end
end
I've found an easier solution which is not related to the OS you are using!
This for Ruby:
<%= link_to 'print', 'your_link_here', :onclick => 'window.print();return false;'%>
And it equivalence in HTML:
<a onclick="window.print();return false;" href="your_link">print</a>
Thank you all for putting your time on this.
See this page for reference: https://technet.microsoft.com/en-us/library/cc731926(v=ws.11).aspx you would need a Line Printer Daemon (LPD) running on the Windows Machine. And would then be able to issue the command. You might need to change some of your security settings. I have not used Rails in a Windows machine in a long time so I am not too sure if the security settings affect it.
Are you sure the machine where you are printing has a Line Printer Daemon running?
From the page I linked above:
This example shows how to print the "Document.txt" text file to the
LaserPrinter1 printer queue on an LPD host at 10.0.0.45:
Lpr -S 10.0.0.45 -P LaserPrinter1 -o Document.txt
Hope that helps or guides you in the right direction.

Ruby and Sinatra: where does this extra string come from and how to eliminate it?

Part of the code in "routes.rb",
...
post '/csr' do
text = PkiSupport::display_csr('/etc/pki/subordinate_ca.csr')
erb :download_csr, :locals => { :csr => text }
end
In "PkiSupport.rb"
...
def display_csr(csr_file)
text = `more #{csr_file}`
return text
end
In "download_csr.erb"
...
<form id="csr-form" action="<%= url "/subordinate_ca/csr" %>" method="post">
<h4>csr</h4>
<textarea cols="80" rows="36" name="csr">
<%= csr %>
</textarea>
</form>
The idea is very simple, when user chooses "/csr", shell command "more ..." will be executed and the output string shown in the textarea of a form.
It does show up correctly, but contains extra preceding string (below), which is anything ahead of "-----BEGIN...". So how to prevent it?
::::::::::::::
/etc/pki/subordinate_ca.csr
::::::::::::::
-----BEGIN CERTIFICATE REQUEST-----
MIIFATCCAukCAQAwaDETMBEGCgmSJomT8ixkARkWA2NvbTETMBEGCgmSJomT8ixk
ARkWA3h5ejEQMA4GA1UECgwHWFlaIEluYzESMBAGA1UECwwJTWFya2V0aW5nMRYw
FAYDVQQDDA0xMC4xMC4xMzAuMTU4MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIIC
CgKCAgEAruWYRn7mjZkHeD+PPLpMSBRoYnLKNvYMte9XneFDh1TItLolYhM4bmWX
gewKOO9+kNY21CoVu1jYZ3q9WitgJlS3tMHPhc6IjuY9DfQ58aeJaZHO8+ISE3Op
l6xNcaxOeHXMlVgdeX4ouyzB2ykJVhu1KtE+XTKilUu6nIrH6ETHrxelBs36Hu1q
...
Thanks.
Most likely, your culprit line of code is this one:
text = `more #{csr_file}`
That code forks and runs the standard Unix more program. Some versions of more will detect if they're run from another program, and output things slightly differently. That's what you're seeing here.
The quickest fix would be to change that line to
text = `cat #{csr_file}`
cat doesn't try to be as smart as more and will give you just the contents of the file.
Now, that said, there's no reason why your Ruby program needs to run a separate program just to read the contents of a file - Ruby has support for reading files directly. So the best fix would be to change that line to:
text = File.read(csr_file)
That will be faster and more portable.

rails translation missing error

I have set flash message in my controller like this
flash[:error] = t 'auth.login.empty'
My en.yml file has
en:
auth:
login:
success: "Successfully logged in"
empty: "Empty field cannot accespted"
error: "Username and password doesn't match"
All are two space indent
I am getting flash as translation missing: en.auth.login.empty
Whether i have to make some configuration changes.
I just ran into this.
A key I was setting at the top of my file was being over-written later on in the file:
# This was showing up as missing
invite:
intent_msg: "Test intent message."
# because waaaay farther down the file I had the following:
invite:
button_text: "<i class='fi-mail'></i> Send Invite"
Even though the two translations are for different keys, the second one was killing off the first one.
So now I have this:
invite:
intent_msg: "Test intent message."
button_text: "<i class='fi-mail'></i> Send Invite"
And all is well again.
Watch out for that one folks.
Your code was actually indented with tabs for the success, empty and error keys. I have fixed this up now.
Please ensure that you are really using spaces. There's no other reason that I know of as to why this would break.

Rails Display Current Facebook Share Count

so I'm trying to display the current facebook share count in a Rails application. I keep getting the "can't convert string to text" error when trying to grab the current URL in my Rails app.
The code works if I put in something like facebook_shares("http://www.google.com")
The code does not work if I use facebook_shares("#{request.protocol}#{request.host_with_port}#{request.fullpath}")
Not sure how to fix this problem
Here is my current code...
helper.rb:
def facebook_shares(url)
data = Net::HTTP.get(URI.parse("http://graph.facebook.com/?ids=#{URI.escape(url)}"))
data = JSON.parse(data)
data[url]['shares']
end
view.html.erb:
<% current_url = "#{request.protocol}#{request.host_with_port}#{request.fullpath}" %>
<%= facebook_shares(current_url) %>
When I run this I get a "can't convert string into integer" error. It works if I do the code below:
<% current_url = "http://www.google.com" %>
<%= facebook_shares(current_url) %>
Super lost...
data[url]['shares'] part is suspicious. Eithere data[url] gives you Array and when you are trying ['shares'] on that Array you are getting the error,which is obvious. Or data itself is Array of something... Thus data[url] throws the error. So inspect first how data is looks like. This error is coming as Array#[] don't allow string inside []. See the below demo code:
arr = [1,2]
arr['foo']
# ~> -:2:in `[]': no implicit conversion of String into Integer (TypeError)
# ~> from -:2:in `<main>'
I figured it out. This was a horrible oversight by myself :p.
I'm in development running on a local server, so I'm pulling localhost:3000/something.
Pushing this and running the function in production works fine. Sorry everyone, but thanks for the help!

Aptana Studio 3 Snippet Around Selection

So I have recently switched from Dreamweaver to Aptana Studio 3 and I have been playing around with the whole custom snippet feature. For the life of me though I cannot figure out how to take a selection/highlighted text and wrap it with my own custom code and/or text. I have looked around the internet for three days now and cannot find anything regarding snippets. I have found some things using commands and key combinations, but I am wanting to create and use a snippet and trying to modify what I have found is not producing good fruit.
I have been able to create my own category and some basic snippets that insert straight text, but nothing that uses a selection.
I have absolutely NO experience with Ruby so forgive me if what follows is completely atrocious. I have more experience with PHP, HTML, Javascript, Java, etc. Here is what I have so far.
snippet "Selection Test" do |snip|
snip.trigger = "my_code"
snip.input = :selection
selection = ENV['TM_SELECTED_TEXT'] || ''
snip.expansion = "<test>$selection</test>\n"
snip.category = "My Snippets"
end
I haven't done much with custom Snippets, but if it helps, there is an example in the HTML bundle of a snippet that surrounds the selected text with <p></p> tags when you do Ctrl + Shift + W. You can see the code for it in snippets.rb in the HTML bundle:
with_defaults :scope => 'text.html - source', :input => :none, :output => :insert_as_snippet do |bundle|
command t(:wrap_selection_in_tag_pair) do |cmd|
cmd.key_binding = "CONTROL+SHIFT+W"
cmd.input = :selection
cmd.invoke do |context|
selection = ENV['TM_SELECTED_TEXT'] || ''
if selection.length > 0
"<${1:p}>${2:#{selection.gsub('/', '\/')}}</${1:p}>"
else
"<${1:p}>$0</${1:p}>"
end
end
end
end
I fiddled around with putting it into the PHP bundle for a few minutes under CTRL + Shift + P and got it working in HTML files, which was not my goal... but was progress. I may play around with it some more later, but in the meantime, maybe you know enough after all of your research to get something put together. I would be interested to see your results if you get this figured out.

Resources