Using Vim to repair files with incorrect character encoding/representation
Consider you have a file that uses improper encoding on special characters. Example: You see the latin1 version "ñ
" for the UTF-8 "ñ
" but the file itself is stored as UTF-8 (meaning that the UTF-8 bytes are doubly encoded).
You can fix that easily with Vim:
vim broken.file
Now you tell vim that the file's encoding is actually latin1
(you can see what Vim is currently using by saying only :set fileencoding
):
:set fileencoding=latin1
Write and reload the file:
:w
:e
All should be good now.
Adjust to your n...
Test whether a form field exists with Cucumber and Capybara
The step definition below lets you say:
Then I should see a field "Password"
But I should not see a field "Role"
Here is the step definition:
Then /^I should( not)? see a field "([^"]*)"$/ do |negate, name|
expectation = negate ? :should_not : :should
begin
field = find_field(name)
rescue Capybara::ElementNotFound
# In Capybara 0.4+ #find_field raises an error instead of returning nil
end
field.send(expectation, be_present)
end
Note that you might have to adapt the step defi...
Why your javascripts should be executed after the dom has been loaded
Most of the JavaScript snippets have code that manipulates the DOM. For that reason dom manipulating javascript code should have been executed after the DOM has loaded completely. That means when the browser has finished HTML parsing and built the DOM tree. At that time, you can manipualte the DOM although not all resources (like images) are fully loaded.
The following snippets show how you can do this with plain JavaScript, jquery or prototype ([dom ready ...
How to combine greps on log files opened with tail -f
In order to chain greps on log files that are opened via tail -f test.log
you have to use the --line-buffered
command line option for grep
.
Imagine you have the following content in your log file.
# content for log/test.log
test foo
bar
test foo bar baz
bla
Now if you would like to grep for lines that contain foo but not bar, you can use the following command chain:
$ tail -f log/test.log | grep --line-buffered "foo" | grep -v "bar"
Output:
test foo
How to create Excel sheets with spreadsheet gem and use number formats for cells like money or date
The following snippet demonstrates how you could create excel files (with spreadsheet gem) and format columns so that they follow a specific number format like currencies or dates do.
require 'rubygems'
require 'spreadsheet'
Spreadsheet.client_encoding = 'UTF-8'
book = Spreadsheet::Workbook.new
sheet1 = book.create_worksheet :name => 'test'
money_format = Spreadsheet::Format.new :number_format => "#,##0.00 [$€-407]"
date_format = Spreadsheet::Format.new :num...
Enabling view rendering for controller specs
Views are normally (for good reason) not rendered in controller specs. If you need it to happen, use:
RSpec 1 (Rails 2):
RSpec 2 (Rails 3):
Note that you can't use that inside it
blocks but need to put it in the nesting example group, like this:
describe '#update' do
cont...
colszowka/simplecov - GitHub
Code coverage for Ruby 1.9 with a powerful configuration library and automatic merging of coverage across test suites.
Note that rcov won't ever have support for Ruby 1.9, you're supposed to use rcov for 1.8 and simplecov for 1.9.
New geordi script: migrate-all
Use the command geordi migrate
to migrate your databases and to prepare them before running tests. The abbrevation geordi m
works as well.
- It will run
rake db:migrate
if parallel_tests does not exist in your Gemfile - Otherwise it runs
b rake db:migrate
and then executesb rake parallel:prepare
if parallel_tests was found in your Gemfile.
How to revert features for deployment, merge back, and how to stay sane
Removing features and merging those changes back can be painful. Here is how it worked for me.\
tl;dr: Before merging back: reinstate reverted features in a temporary branch, then merge that branch.
Scenario
Consider your team has been working on several features in a branch, made many changes over time and thus several commits for each feature.\
Now your client wants you to deploy while there are still stories that were rejected previously and can't be deployed.
...
How to organize and execute cucumber features (e.g. in subdirectories)
In cucumber you are able to run features in whatever directory you like. This also includes executing features in subdirectories. There are only some things you have to take care of.
By default, cucumber loads all *.rb
files it can find (recursively) within the directory you passed as argument to cucumber.
$ cucumber # defaults to directory "features"
$ cucumber features
$ cucumber my/custom/features/dir
So, if you would like to organize features in subdirectories, you won't have *any problems when running the whole test...
Repeat an element on every printed page with CSS
Firefox, Opera and Internet Explorer will repeat elements with position: fixed
on every printed page (see attached example).
The internet knows no way to do this in Webkit browsers (Chrome, Safari). These browsers will only render the element on the first printed page.
Make Makandra Consul work with RSpec 2.x and Rails 3.x
To make the RSpec matcher of the authorization solution Consul work with Rspec 2.x read the following blog post.
How to click hidden submit buttons with Selenium
In your Cucumber features you can't really click hidden elements when using Selenium (it does work for a plain Webrat scenario, though).
Unfortunately you need to hack around it, like this:
When /^I press the hidden "([^\"]+)" submit button$/ do |label|
page.evaluate_script <<-JS
$('input[type=submit][value="#{label}"]').show().click();
JS
end
If your button is nested into a container that is hidden this will not do the trick. You need a more complex method to also show surrounding containers:
When /^I pre...
Update: Aggregated RSpec/Cucumber test coverage with RCov
Our rcov:all
task for aggregated RSpec/Cucumber coverage was overhauled extensively. Among other things it now works for Rails 2 and 3 and has an option to ignore shared traits.
RCov: The difference between "code coverage" and "total coverage"
Code coverage is the ratio of code lines kissed by a test vs. the total number of lines in your source files. This sounds meaningful, but isn't.
Total coverage additionally ignores whitespace and comments when computing the coverage ratio, which is what you want.
Fix AssociationTypeMismatch
When you're getting this error, one possibility is that you've created a select field for an association instead of the associated object's id. Example:
form.select :unit, Unit.for_select
will be expected to deliver a real Unit
object, whereas
form.select :unit_id, Unit.for_select
will make Rails typecast the String value from the select field to the unit's ID.
Managing Rails locale files with i18n-tasks
When internationalizing your Rails app, you'll be replacing strings like 'Please enter your name'
with t('.name_prompt')
. You will be adding keys to your config/locales/*.yml
files over and over again. Not to miss any key and place each at the right place is a challenging task.
The gem i18n-tasks
has you covered. See its README for a list of things it will do for you.
Note
The
i18n-tasks
gem does not understand aliases and will duplicate all referenced data when it writes locales. If yo...
Request a gzipped response from a web server using Wget
To reduce download time, application servers usually serve content using gzip compression, if the browser supports it.
When using a tool like Wget to explicitly download an application's response, the server responds with the uncompressed version:
wget http://example.com/
If you are curious about the compressed file's size, pass the corresponding HTTP header:
wget --header="accept-encoding: gzip" http://example.com/
Embed Google Analytics code for some environments only
When you use google analytics to track your visitors interactions, you should ensure that it runs on your production site only. Otherwise it will spoil your statistics. To prevent this, test for the right environment and place the JS-code afterwards:
- if Rails.env.production?
:javascript
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXXX-X']);
_gaq.push(['_trackPageview']);
...
How to fix "unknown role" errors in Capistrano recipes
When you have a complex recipe setup with multistage deployment you may run into this error:
`role_list_from': unknown role `something' (ArgumentError)
Consider this task definition:
namespace :foo do
task :bar, :roles => :something do
# do crazy stuff
end
end
Whenever we call foo.bar
in our recipe, Capistrano will fail if you deploy to a stage where none of the servers has the role the error complains about, "something
" in this case.
However, you can [hack around it](http://groups.google.com/group/ca...
Scenario outlines in Cucumber
Scenario outlines allow us to more concisely express repetitive examples through the use of a template with placeholders.
Graticule computes NULL distance for some records (and how to fix that)
The SQL code generated by Graticule's spherical distance computation is insufficient and can lead to NULL
distances in edge cases.
The reason for this is that MySQL is performing several sine and cosine computations which can result in slight rounding errors -- which is usually okay. Rarely, though, for the exact center of the given circle, it is then asked to compute the arc cosine of a result like 1.0000000001.
Since this i...
ActsAsTaggableOn: Cache tag lists
For performance improvements (and to remove the need for eager loading), the ActsAsTaggableOn gem supports caching your tag lists directly in your model. To enable this, simply add a cached_tag_list
column to your table.
Example:
class Company < ActiveRecord::Base
acts_as_taggable_on :categories
end
The cache column has to be named cached_category_list
.
Existing data
If you already have existing data, you have to save all records with tags once, after you've added the ...
Error "execution expired (Timeout::Error)" when using Selenium and Webmock
If you get the above error when running tests in bulk (but not individually), it's actually the fault of Webmock.
Updating Webmock to version 1.7+ fixes this.