How to hide your selenium browser window with "headless"
Note: While the solution in this card should still work, we prefer another solution now: Hide your Selenium browser window with a VNC server.
If you would like to hide the annoying selenium browser window that always gets the focus and prevents you from working, you can use the headless gem. This note provides some instructions how you can get it to work with your cucumber accepta...
RSpec 2.6 supports "any_instance" now
This finally works:
User.any_instance.should_receive(...)
as does
User.any_instance.stub(...)
Note: You won't have RSpec 2.6 if you're still working on Rails 2.
How to use different encodings for text in HTTP headers
In order to use different encodings than ASCII for HTTP headers use the following syntax:
Header-Key: Header-Value; Parameter-Name*=utf-8''parameter_value_in_utf8_and_encoded_chars
Concrete example how to use an utf8 encoded filename for file downloads (with fallback):
Content-Disposition: attachment; filename="aepfel"; filename*=utf-8''%c3%a4pfel
Linux: Create file of a given size
Sometimes you need a file of some size (possibly for testing purposes). On Linux, you can use dd
to create one.
Let's say you want a 23 MB file called test.file
. You would then run this:
dd if=/dev/zero of=test.file bs=1048576 count=23
The block size (bs
) is set to 1 MB (1024^2 bytes) here, writing 23 such chunks makes the file 23 MB big.\
Adjust to your needs.
This linux command might also come in handy in a Ruby program. It could be used like:
mb = 23
mb_string, _error_str, _status = Open3.capture3('dd if=/dev/zero...
Running the Awesome window manager within Gnome
Note: Consider using MATE instead of Gnome 3 on newer system
Awesome is a very good tiling window manager that provides neat features like automatic layouting of windows, good multi-display support with per display workspaces and more. Unfortunately, it is only a window manager, and lacks a lot of Gnome's conveniences like the network manager, application menus, automatic updates etc.
Fortunately, Gnome allows you to selectively replace only the win...
Check gem dependencies before installation
With gem dependency
it is possible to check the dependencies for your gem before you install it.
Here is an example output for Nokogiri:
Gem nokogiri-1.4.4
hoe (>= 2.6.2, development)
minitest (>= 1.6.0, development)
racc (>= 0, development)
rake-compiler (>= 0, development)
rexical (>= 0, development)
rubyforge (>= 2.0.4, development)
Configuring ActionMailer host and protocol for URL generation
When you generate a URL in a mailer view, ActionMailer
will raise an error unless you previously configured it which hostname to use.
There are two options to set the default_url_options
of ActionMailer:
- Hardcoded solution (preferred solution when using Rails with ActiveJob/Sidekiq or Cronjobs)
- Dynamic solution
1. Hardcoded solution
When you are sending mails from outside the request cycle, e.g. ActiveJob/Sidekiq or Cronjobs, y...
Fix slow specs using SOLR
I've recently encountered a weird problem with specs making lots of SOLR queries using the acts_as_solr
plugin: After a certain number of specs, exactly one spec suddenly took over 30 seconds to finish.
It turns out that for some reason, the SOLR server seemed not to close its HTTP connections properly. After the maximum number of connections was reached, the next spec needed to wait for an old connection to time out.
I'm not exactly sure why this happened, why it only seems to be happening in specs and which part of the code is actually...
Traverse large XML files with Nokogiri
If you need to parse a large XML file (> 20 MB or so), you should parse it in chunks, otherwise it will need lots of memory.
Nokogiri offers a reader that lets you parse your XML one node at a time.
Given an XML library.xml
with this content
<library>
<book>
<title>...</title>
<author>...</author>
</book>
<book>
...
</book>
...
</library>
you can for example loop over all books with
def each_book(filename, &block)
File.open(filename) do |file|
...
Capybara steps to match stuff within any selector
These steps are now part of Spreewald.
Since Capybara 0.4.1 a within
scope will only look at the first element that matches. We find this behavior to be impractical, but it is by design.
In order to perform a test or action in all matching elements, do not use within
but prefer the attached "inside any
" Cucumber steps like these:
When I follow "Foo" inside any "table"
Then I should see "Bar" inside any "li"
Test that a string of text is (not) linked in Webrat or Capybara
The step definition below allows you to write:
Then I should see a link labeled "Foo"
But I should not see a link labeled "Bar"
Webrat
Then /^I should( not)? see a link labeled "([^"]*)"$/ do |negate, label|
expectation = negate ? :should_not : :should
response.send(expectation, have_selector("a", :content => label))
end
Capybara
Then /^I should( not)? see a link labeled "([^"]*)"$/ do |negate, label|
expectation = negate ? :should_not : :should
page.send(expectat...
How to build the perfect number of blank records for a nested form
When you render a nested form for a Movie
which has_many :actors
, you want to render the right number of blank Actor
forms. The right number means:
- A minimum number of blank forms so the user can add more
Actors
to an existingMovie
, e.g. 2. - A minimum total number of forms (both blank and pre-filled) so the user sees more than just 2 blank
Actor
forms when she is enteringActors
for the first time, e.g. 5.
For the example above, this is the desired progression of the number of blank forms:
| Number of actors | Number of ...
Force SSH client to use password authentication instead of public key
To test if you can connect to a host using password authentication and explicitly deny public key authentication:
ssh -o PreferredAuthentications=password -o PubkeyAuthentication=no user@host
This also works for Secure Copy:
scp -o PreferredAuthentications=password -o PubkeyAuthentication=no local.file user@host:/path/to/remote.file
Run Selenium tests in Chrome instead of Firefox
Here is how to switch your Selenium to Chrome:
- Make sure you've got a recent version of chromedriver in your
$PATH
See also geordi chromedriver_update which is automatically executed before every usage of geordi cucumber
.
- Register Driver:
Create a file features/support/capybara.rb
with the following content for recent version of Capybara:
Capybara.register_driver :selenium do |app|
Capyb...
RSpec: Stubbing a method that takes a block
If you stub
a method or set expectations with should_receive
these stubbed methods may also yield blocks. This is handy if the returning object is receiving a block call.
Consider this, where you cannot say and_return []
because of the block:
def crawl_messages
Message.find_in_batches do |messages|
messages.each(&:crawl)
end
end
It works similar to and_return
-- just use and_yield
:
describe '#crawl_messages' do
it 'should proc...
Change the timestamp of a file in Ruby
This is somewhat similar to the touch
command of Linux:
FileUtils.touch 'example.txt', :mtime => Time.now - 2.hours
If you omit the :mtime
the modification timestamp will be set to the current time:
FileUtils.touch 'example.txt'
You may also pass an array of filenames:
FileUtils.touch %w[ foo bar baz ], :mtime => Time.now - 2.hours
Non-existent files will be created.
Force Google Chrome to run in English on Linux
If you need Google Chrome to run in English, and your system locale is a non-English one, you have two options:
- Switch your system to an English locale
- Head over to
/opt/google/chrome/locales/
and remove any.pak
files except those starting with “en
”. They reappear when Chrome gets updated.
This may help you running your Selenium tests using the Chrome driver on applications that choose the language from what the browser sends as preferred language (which Chrome guesses from your system locale).
What to do when Google only syncs some of your contacts
When some of your Google contacts are no longer synchronized with your e-mail client or mobile phone, those contacts are not in a group "My Contacts". Google only syncs contacts in that group.
In order to fix this:
- Open Google Contacts
- Select all contacts (there's a link)
- Press "Move to My Contacts"
Note that when you are using Mozilla Thunderbird with the Google Contacts add-on, Thunderbird won't add new contacts into the "My Co...
How to fix: undefined method `specifications' (caused by RubyGems 1.8)
Sometimes, when running a rake task, RubyGems 1.8.5 raises an error:
rake aborted!
undefined method `specifications' for "/usr/lib/ruby/gems/1.8":String
This has been fixed since May 31 but is still not available as a new RubyGems version.
Either wait for a new version to eventually come out, downgrade to some really old version (1.6.2 works for some) or apply the fix manually:
- Find your rubygems.rb -- mine was located at `/usr/local/lib/sit...
RubyMine crashes Ubuntu 11.04 window decorator on exit
My RubyMine (and it seems like many other Java GUI applications) crashes the Compiz window decorator almost every time on exit. This also seems to happen for the Unity decorator.
Update: The commited fix from below seems to have made it into the stable Ubuntu repository.
Easy mode
You can restore window decorations by executing this command:
gtk-window-decorator --replace &
This is only a temporary fix.
Hard mode
Also, there is a committed fix that is n...
How to use helper methods inside a model
Simple
If you want to use a helper_method my_helper_method
inside a model, you can write
ApplicationController.helpers.my_helper_method
When using multiple helpers
delegate :helpers, to: ApplicationController
helpers.my_helper_method
helpers.my_other_helper-method
More flexible
If you need a bit more flexibility, for example if you also need to override some methods, you can do this:
class HelperProxy < ActionView::Base
include ApplicationController.master_helper_modu...
Using RSpec's late resolving of "let" variables for cleaner specs
Consider the following:
describe '#something' do
context 'with lots of required arguments' do
it 'should work' do
subject.something(:foo => 'foo', :bar => 'bar', :baz => 'baz').should == 'Hello world'
end
it 'should work again' do
subject.stub :target => 'universe'
subject.something(:foo => 'foo', :bar => 'bar', :baz => 'baz').should == 'Hello universe'
end
it 'should work yet again' do
subject.stub :target => 'multiverse'
subject.something...
Helpers to render (money) amounts
When rendering a number, you want to pretty up the string coming from #to_s
:
- Render
0.0
as0
- Sometimes require a minimum number of digits after the decimal separator
- Change the decimal separator from
.
to,
in some European countries - Render a dash if the given amount is
nil
The attached helper that does just that. Some usage examples with their resulting strings:
Invocation | Result |
---|---|
amount(0) |
0 |
amount(0.0) |
0 |
amount(0.5) |
0,5 |
amount(1.5, :minimum_precision => 2) |
1,50 |
`amo... |
Why developers should be force-fed state machines
Most web applications contain several examples of state machines, including accounts and subscriptions, invoices, orders, blog posts, and many more. The problem is that you might not necessarily think of them as state machines while designing your application. Therefore, it is good to have some indicators to recognize them early on. The easiest way is to look at your data model.