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.
Order in which RSpec processes .rb files
Because your examples should not change global state, you should not need to care about the order in which RSpec processes your .rb
files. However, in some cases you might want to know.
RSpec 3
- Runs
.rb
files in alphabetical order of their file paths by default (or when you specify--order defined
). - You run t...
Stubbed class methods in RSpec 1 remain stubbed in other examples
I encountered a bug in RSpec 1.x where stubbed class methods ("static methods") would not be unstubbed before the next example, causing it to fail. This behavior can come and go as you edit your specs, since this can change the order in which RSpec evaluates your .rb
files.
I was not able to find a fix for this behavior. Calling #rspec_reset
und #unstub!(:method)
on the class after the example did not help. I know for sure that stubbing static methods has not been a problem in many other projects. I encountered the bug while working o...
New Cucumber Factory makes it easier to associate records
I pushed a new version of the Cucumber Factory gem. This new release lets you refer to a previously created record by any string attribute:
Given there is a movie with the title "Before Sunrise"
And there is a movie with the title "Limitless"
And there is a movie with the prequel "Before Sunrise"
Note how we didn't have to explicitly give the prequel a name in the example above. This is still possible, but will rarely be necessary now:
Given "Before Sunrise" is a movie with...
Example .ssh/config file
Attached you can find an example ~/.ssh/config
file which makes working with SSH more pleasant. It contains several tweaks:
- Default settings
- Defining host aliases in your SSH config
- Don't let your SSH session die
After you download the file to ~/.ssh/config
, edit the file in a text editor to tailor it to your individual needs.
A nicer way to run RSpec and/or Cucumber
geordi, our collection of awesome shell scripts, has been extended by three scripts to help you call RSpec or Cucumber:
cuc
This script runs Cucumber the way you want it:
- Prints some line feeds to easily find your test results when you come back to the console later
- Configures Cucumber to use cucumber_spinner if it is available in your
Gemfile
- Runs Cucumber under
bundle exec
- Uses an old version of Firefox for Selenium (Javascript) features...
Merging two arbitrary ActiveRecord scopes
(Rails has a method ActiveRecord::Relation#merge
that can merge ActiveRecord scopes. However, its behavior has never been clear, and in Rails 7 it still discards conditions on the same column by the last condition. We discourage using #merge
!)
The best way to merge ActiveRecord scopes is using a subquery:
scope_a.where(id: scope_b)
It is a little less concise than #merge
, but unambiguous.
Example
Assume a model where a deal has many documents:
class Deal < ApplicationRecord
has_many :...
List directories ordered by size (with human-readable output)
You know there is the du
command to fetch the disk usage of a directory (“.
” in this example). By default, output is sorted by directory name, not size:
du -h --max-depth=1 .
40K ./a
2.3G ./b
3.1M ./c
500M ./d
2.8G .
To see which directories take up the most (or least) space you can order them by size like this (the -h
switch does the magic of understanding humanized size formats):
du -h --max-depth=1 . | sort -h
40K ./a
3.1M ./c
500M ./d
2.3G ./b
2.8G .
Note that you will need to...
How to test resource_controller hooks
When using the resource_controller gem you often hook onto events like this:
update.before do
do_something
end
For testing such things in your controller you should -- as always -- not trigger something that eventually calls the thing you want.\
Instead, in your specs, have resource_controller run those hooks like it does itself. Like that:
describe 'before update' do
...
SSL: Build a Certificate signing request (CSR)
In order to request a SSL certificate from any dealer, you usually need a CSR certificate. As both the CSR as well as key are created in this step, make sure you save this certificate on a trusted, secure machine only. Usually this is your production environment.
Run this on the server (not on your machine) as root.\
Replace your-domain.tld with the domain you request the certificate for and YYYY with the current year so you will not have any conflicts when requesting a certificate next year.
openssl req -new -sha256 -out www.your-dom...
Soft-scroll to an anchor with jQuery
This snippet makes links that refer to an anchor (like "<a href="#something">...</a>
") scroll softly to it.\
In this example we only do it for links that also own a data-animate
attribute.
$('a[href^="#"][data-animate]').live('click', function() {
var hash = $(this).attr('href');
var offset = $(hash).offset();
if (offset) {
$('html, body').animate({ scrollTop: offset.top }, 'slow');
location.hash = hash;
return false;
}
});
Note that this could basically work for any element whos...