Capybara - The missing API
The Capybara API is somewhat hard for parse for a list of methods you can call on a Capybara node. Below you can find such a list. It's all copied from the Capybara docs, so all credit goes to the Capybara committers.
When you talk to Capybara from a Cucumber step definition, you always have page as the document root node, or whatever you scoped to by saying within(selector) { ... }. You can select child notes by calling page.find(selector) or page.all(selector). You can call the same ...
How to grep through the DOM using the Capybara API
When your Cucumber feature needs to browse the page HTML, and you are not sure how to express your query as a clever CSS or XPath expression, there is another way: You can use all and find to grep through the DOM and then perform your search in plain Ruby.
Here is an example for this technique:
Then /^I should see an image with the file...
How to diff two strings in Ruby
When you need to use diff in either some Ruby code or your Rails app, use the differ gem.
puts Differ.diff "foo", "boo"
# => {"boo" >> "foo"}
Usage
There are several variants available, all using the base method diff(to, from, separator = "\n").
You have diff_by_line, diff_by_word, diff_by_char and may of course use your own separator:
puts Differ.diff 'Hauptsatz, und mein Nebensatz.', 'Hauptsatz, und dein Nebensatz.', ','
# => Hauptsatz,{" und dein Nebensatz." >> " un...
JSONP - Wikipedia
Under the same origin policy, a web page served from server1.example.com cannot normally connect to or communicate with a server other than server1.example.com. An exception is the HTML <script> element. Taking advantage of the open policy for <script> elements, some pages use them to retrieve Javascript code that operates on dynamically-generated JSON-formatted data from other origins. This usage pattern is known as JSONP. Requests for JSONP retrieve not JSON, but arbitrary JavaScript code.
Use Capybara on any HTML fragment or page
I think this pattern is really useful not just for upgrading suites from Webrat, but really anywhere you have an HTML fragment or string that you’d like to use Capybara’s matchers on.
Hide your Selenium browser window with a VNC server
This is now part of geordi. Please don't follow the instructions below, if you use geordi.
Inspired by the recent headless Selenium note, I found yet another solution for the problem to hide your selenium tests away.
This has the advantages
^
- not to require a gem (so you do not force this on others)
- to allow you to take a look at the running webdriver if necessary
Simply make a script th...
simple_format helper for Javascript
The Javascript code below is a rough equivalent to the simple_format helper that ships with Rails:
function simpleFormat(str) {
str = str.replace(/\r\n?/, "\n");
str = $.trim(str);
if (str.length > 0) {
str = str.replace(/\n\n+/g, '</p><p>');
str = str.replace(/\n/g, '<br />');
str = '<p>' + str + '</p>';
}
return str;
}
Unlike the Rails helper, this does not preserve whitespace. You probably don't care.
A few hints when upgrading to Ruby 1.9
Note: If you are currently working with Ruby 1.8.7 or 1.9.3, we recommend to upgrade to Ruby 2.1 first. From our experience this upgrade is much smoother than the jump from 2.1 and 2.2, while still giving your the huge performance gains of Ruby 2. Also, if you're on Ruby 1.8.7, we recommend to skip a troublesome upgrade to 1.9.3 and go straight to 2.1.
When trying to make a Rails app run on Ruby 1.9, you're likely to encounter several issues. Here are a few solutions (obviously not exhaustive):
When running `bundle ...
Rails 3: Make "link_to :remote => true" replace HTML elements with jQuery
In Rails 2, you could use link_to_remote ... :update => 'id' to automatically replace the content of $('#id').
To do the same in Rails 3, include usual rails-ujs JavaScript, and put this into your application.js:
$(function() {
$('[data-remote][data-replace]')
.data('type', 'html')
.live('ajax:success', function(event, data) {
var $this = $(this);
$($this.data('replace')).html(data);
$this.trigger('ajax:replaced');...
Virtual attributes for date fields
Note that this card is very old. You might want to use ActiveType for your auto-coerced virtual attributes instead.
We sometimes give our models virtual attributes for values that don't need to be stored permanently.
When such a virtual attribute should contain Date values you might get unexpected behavior with forms, because every param is a string and you don't get the magic type casting that ...
Shell script to generate a Git commit with Pivotal Tracker story ID and title
We usually generate our commit messages from Pivotal Tracker IDs and titles, like
[#15775609] Index view for conflicts
The geordi command commit automates this. (See: Pretty Commit messages via geordi).
Just run geordi commit and it will connect to PT and let you select from a list of all started and finishes stories. Then it runs git commit with the generated message (i.e. all staged changes will be commited).
When running for the first time, Geordi will request your PT...
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...
Popular mistakes when using nested forms
Here are some popular mistakes when using nested forms:
- You are using
fields_forinstead ofform.fields_for. - You forgot to use
accepts_nested_attributesin the containing model. Rails won't complain, but nothing will work. In particular,nested_form.objectwill benil. - The
:reject_ifoption lambda in youraccepts_nested_attributescall is defined incorrectly. Raise the attributes hash given to your:reject_iflambda to see if it looks like you expect. - If you are nesting forms into nested forms, each model involved ne...
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
Actorsto 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
Actorforms when she is enteringActorsfor 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 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.pakfiles 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).
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...
How to upgrade RubyMine
This card explains how to upgrade an existing RubyMine installation to a newer version. If you're installing RubyMine for the first time, see install RubyMine under Ubuntu. You might also consider installing RubyMine with snap, so it can receive automatic updates (also described in the install card).
This procedure ensures that an update does not totally break your IDE, as it allows you to keep both the previous and the new version of RubyMine:
- [Download the newest version](http://www.jetbrains.com/ruby...
Helpers to render (money) amounts
When rendering a number, you want to pretty up the string coming from #to_s:
- Render
0.0as0 - 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... |
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...
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...
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...
Semantic markup standard for search engines
If you would like to enrich your website with semantic markup like contact data, places or events you should have a look at schema.org. "Search engines including Bing, Google and Yahoo! rely on this markup to improve the display of search results, making it easier for people to find the right web pages."
The following example from the schema.org documentation shows you how to describe a movie with semantic markup:
<div itemscope itemtype ="http://schema.org/Movie">
<h1 itemp...
Matching elements on complex web pages with Webrat
XPath matchers can be combined with CSS-selector matchers. This is really useful if not, for example, the content of an element should be matched but the element itself like in the following example. Here a form is used to display data as default value in its input elements. This can be the case in web applications in which data should be edited easily without additional clicks.
Using StaticMatic for static pages
Update: Staticmatic will not be further developed. They suggest to switch to middleman.
If you need to make a static web page and find yourself missing all your Rails comforts, take a look at StaticMatic.
This works like an extremely stripped down version of Rails, giving you
- HAML
- SASS
- helpers
- partials
When done, everything is simply compiled to s...