Bash: How to only do things in interactive shells
When you print something from within your .bashrc
file you will run into trouble when copying something onto your machine using scp
for example.
This is because the output from your .bashrc
interferes with scp
. The solution is to decide whether the bash shell is started interactively (you start a terminal on your screen) or not (scp
).
if [ ! -z "$PS1" ]; then
# This happens in interactive shells only and does not interfere with scp.
echo "Learn!"
fi
Spreewald 0.8.0 brings a file attachment step
# Attach a file
#
# Example:
#
# Company.new.logo = File.new…
#
# Given the file "…" was attached as logo to the company above
#
#
# Example:
#
# class Gallery
# has_many :images, :as => :owner
# end
#
# class Image
# belongs_to :owner, polymorphic: true
# end
#
# # so container = Image.new; container.file = File.new… , container.owner = object
#
# Given the file "…" was attached as Image/file to the company above
#
#
# Example:
#
# Set updated_at with
#
# Given … above at "2011-11-11 11:11"
#
howto fix spreewald issue „database configuration does not specify adapter (ActiveRecord::AdapterNotSpecified)“
This error occurs when you already have a database.yml
which defines the database for the cucumber
environment instead of test
. (Spreewald database.sample.yml
has changed)
Fix
Change cucumber
to test
in your databse.yml
test: # <---
adapter: mysql2
database: spreewald_test
encoding: utf8
host: localhost
username: root
password: password
Whitelist Carrierwave attributes correctly
Say you have a User
with a Carrierwave attribute #avatar
:
class User < ActiveRecord::Base
mount_uploader :avatar, AvatarUploader
end
When whitelisting the avatar
field in the controller, you might do this:
params[:user].permit(:avatar)
But you probably want this:
params[:user].permit(:avatar, :avatar_cache, :remove_avatar)
In this example:
-
:avatar_cache
allows a newly upload image to persist through form roundtrips in the case of validation errors (something that isn't possibl...
How to find out the type of a model's attribute
When you want to find out the data type of an attribute, you can just use ActiveRecord's columns_hash
method.
It returns a hash of column objects that include a type
attribute (and more database-related information).
Example:
Contract.columns_hash['id'].type
=> :integer
Contract.columns_hash['active'].type
=> :boolean
Contract.columns_hash['updated_at'].type
=> :datetime
FooLimitExceeded Quota problem with OpenStack
If you get a Quota error with OpenStack, it doesn't have to be what it tell.
For example, I've got this message because the RAM Quota was exceed:
2013-11-11 17:13:25 WARNING nova.compute.api [req-bdasdfas-f5d7-4fcd-bf1b-asdfasdf229e ba2c21dadasdfasdf1d6asdfasdfa0f bfe2db2aasdfasdfb8ea686asdfasdfb] Quota exceeded for bfe2db2aasdfasdfb8ea686asdfasdfb, tried to run 1 instances. Cannot run any more instances of this type.
2013-11-11 17:13:25 INFO nova.api.openstack.wsgi [req-bd003113-f5d7-4fcd-bf1b-asdfasdf229e ba2c21dadasdfasdf1d6asdf...
Monitoring a network connection from a remote host
Sometimes you need to monitor a connection from your machine to a specific, single host or network in order to identify which network hop between your machine and the target causes trouble. You can use the following shell script to easily achieve this kind of monitoring.
If the target host is unable to respond to the specified number of ICMP packets, you will get an eMail together with a mtr
to see on which hop the problem occurs.
#!/bin/bash
TARGET=8.8.8.8 # Target host or IP address to be monitored.
MAIL_RECIPIENT=you@exam...
Let the browser choose the protocol
Use protocol independent URLs whenever possible so that the browser will choose the protocol related to the protocol which the page is delivered with.
Example issues
- When your page is delivered via
https
and you provide a youtube video only viahttp
the most browsers (e.g. Firefox, Chrome) won't display the video. - When you deliver your youtube video via
https://youtu.be/jyElDp98HdI
your test which checks that the embeded video is rendered in the view will fail because your test server doesn't use https
Solution
Let your lin...
Font Combiner
Font Combiner offers a way to tweak and adjust any TTF or OTF font (license permitting), by bringing in font glyphs as vector shapes, providing a completely overhauled font generated to the user's specification with alternative metrics options, alternative hinting types, kerning and spacing options and the facility to make any average free font look great.
Stubbing out external services with an embedded Sinatra application
One of many useful techniques when your test suite needs to talk to a remote API.
Enable NewRelic monitoring [for Rails] on specific hosts only
If you need to enable NewRelic monitoring on certain machines within the same Rails environment, a simple solution is to utilize the respective hostnames of you machines.
For example, if you have 8 application servers (e.g. app1.example.com
, app2.example.com
, ...) and want to enable NewRelic on app1
and app2
only, utilize those steps to do so:
- Put the attached file into your config directory (
config/custom_new_relic_configuration.rb
). - Specify on which hosts NewRelic should be enabled (see
NEWRELIC_HOSTS
constant and list ...
A simpler default controller implementation
Rails has always included a scaffold
script that generates a default controller implementation for you. Unfortunately that generated controller is unnecessarily verbose.
When we take over Rails projects from other teams, we often find that controllers are the unloved child, where annoying glue code has been paved over and over again, negotiating between request and model using implicit and convoluted protocols.
We prefer a different approach. We believe that among all the classes in a Rails project, controllers are some of the hardest to...
Fix "An error occurred while installing debugger-linecache" with Ruby 1.9.3
You're better off using debugger-ruby_core_source
:
gem install debugger-ruby_core_source
If you can't do this, try the following.
Here is how to fix the following error when installing the debugger
gem fails:
Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension
Note: The following example is for a project using Ruby 1.9.3-p448 -- adjust accordingly for your project.
-
Fetch the source for your Ruby version, if you do not yet have it:
rvm fetch ruby-1.9.3-p448
-
Install t...
How to not repeat yourself in Cucumber scenarios
It is good programming practice to Don't Repeat Yourself (or DRY). In Ruby on Rails we keep our code DRY by sharing behavior by using inheritance, modules, traits or partials.
When you reuse behavior you want to reuse tests as well. You are probably already reusing examples in unit tests. Unfortunately it is much harder to reuse code when writing integration tests with Cucumber, where you need to...
Geordi: Choose your firefox version for cuc
Geordi 0.16+ supports running selenium tests with project-specific firefox versions.
Just update the gem. It will still default to using the old 5.0.1 firefox. If you want another one, add a file .firefox-version
to your project, containing your preferred version.
geordi cucumber
will prompt (and guide) you to install the given version. You can delete any old installation sitting in /opt/firefox-for-selenium
if you have one.
VCR: Alternative way of mocking remote APIs
If you need to test interaction with a remote API, check out the VCR gem as an alternative to Webmock or stubbing hell.
The idea behind VCR is that is performs real HTTP requests and logs the interaction in a .yml file. When you run the test again, requests and responses are stubbed from the log and the test can run offline.
It's a great way to mock network requests to an external service without going through the pain of log...
Implementing social media "like" buttons: Everything you never wanted to know
So you client has asked you to implement a row of buttons to like the URL on Facebook, Twitter and Google+. Here are some things you should know about this.
0. Security considerations
Each "like" button is implemented by including a Javascript on your site. This means you are running fucking remote code on your page. You are giving Facebook, Twitter and Google+ full permission to e. g. copy user cookies. Check with your client if she is cool with that. Also note that if you're site is suggesting security by operating under HTTPS ...
Enable CSRF protection in Javascript tests
You might not know that Rails disables CSRF protection in tests. This means that if you accidentally forget to send the CSRF token for non-GET requests, your tests will be green even though your application is completely broken (a failed CSRF check usually logs out the user). Rails probably does this because CSRF protection sort of requires Javascript.
You want to enable CSRF protection in Cucumber scenarios that can speak Javascript. To do so, copy the a...
Rails 3/4: How to add routes for specs only
If you want to have routes that are only available in tests (e.g. for testing obscure redirects), you can use the with_routing
helper -- but that one destroys existing routes which may break a specs that require them to work.
To keep both "regular" and test routes, do this:
class MyApplicationController < ActionController::Base
def show
render text: 'Welcome to my application'
end
end
test_routes = Proc.new do
get '/my_application' => 'my_application#show'
end
Rails.application.routes.ev...
How to change the locale of a PostgreSQL cluster
There may be reasons to change the locale of your Postgres cluster. A popular one is your development system's locale being used by default (which may be annoying). Here is how to do that.
Beware: By following the steps below, you will drop and recreate your cluster. You will lose all data (including roles). Instructions below include a procedure for dumping and restoring all cluster data (including roles). While it worked at the time of writing, you should have extra backup strategies for a production database.
- Find the cluster you...
Disable text-transforms in Selenium tests
Using text-transform: uppercase
- especially on form labels - can cause you serious headaches in Selenium tests. Sometimes the web driver will see the uppercase text, sometimes it won't, and umlauts will be a problem as well.
Simply disable it in tests, by
-
adding a body class for tests
%body{'data-environment' => Rails.env}
-
overriding the transforms
[data-environment="test"] * text-transform: none !important
Outlook deletes iCalendar ICS eMails and moves them to trash folder
We sometimes send calender data or tasks using iCalendar (ICS) via eMail as specified in RFC 5545.
Recently, a customer noticed that Outlook automatically moved eMails containing such ICS data to deleted items folder and shows the events as tentative on calendar.
This problem is reported on TechNet, for example.
It ...
Custom RSpec matcher for allowed values (or assignable_values)
In contrast to RSpec's included allow_value
matcher, the attached matcher will also work on associations, which makes it ideal for testing assignable_values
.
Usage example
describe Unit do
describe '#building' do
it 'should only allow buildings that a user has access to' do
building = build(:building)
other_building = build(:building)
unauthorized_building = build(:building)
power = Power.new(build(:user))
Power.with_power(power) do
expect(power).to receive(:buildings).at_least...
Capybara: Trigger requests with custom request method
Preface: Normally, you would not need this in integrations tests (probably that's why it is so hard to achieve), because it is no actual "integration testing". If you use this step, know what you are doing.
Destroying a record with Capybara is not as easy as calling visit user_path(user, method: :delete)
, because RackTest's visit
can only perform GET requests.
With this step you can destroy a records using either Selenium or RackTest. Ex...