RSpec Request Spec to Test Rails / Grape API Functionality
I finally got around to trying Grape – a “RESTful API microframework built to easily and quickly produce APIs for Ruby-based web applications”. This is a project still in baby stages, but has a lot of potential and worth exploring for anyone creating a Rack-based API in Ruby, not necessarily Rails!
Now, after creating a pretty basic API that used HTTP Basic Authentication, I was inclined to write some RSpec tests to make sure my API was working the way I thought it was (.. or because I am obsessed with well-tested, beautiful code..).
After some thought, I decided that the best way to test my API was with RSpec “request” specs. Now, if you are at all relatively new to RSpec (I was a Test::Unit kinda guy before), it might not be completely obvious that “request specs” are basically what I have come to know as “integration tests”, testing high-level functionality that spans multiple controllers and multiple requests – (think: a user’s interaction with the app).
My reasoning for choosing request specs is because I want to test specific API URL endpoints routed the way I expected. (Routing is handled magically by Grape with a simple mount in the config/routes.rb file). API testing just kinda makes sense to handle in request specs.
Anyways, I ran into a couple issues because in REQUEST specs, you do not have access to the @request object (haha?), as you do in controller specs. Now, in order to mock HTTP Basic Authentication, you need to mock the request object to send headers along with the GET request.
Well, solution: It turns out you can pass headers into your get() method! I only wish I had discovered that an hour ago!
Here’s a simple excerpt from my API request specs that shows how to mock the HTTP basic authentication and test your API functionality:
With NO basic auth, it’s just a simple GET request
it 'should return a 401 with no basic auth to /api/v1/rewards' do
get '/api/v1/rewards'
response.code.should == '401'
response.body.should == "Unauthorized - Please check your username and password"
end
To mock the basic auth, simply pass header hash as argument to the GET request! No need to access the request object here.
it 'should return a 200 with valid basic auth to /api/v1/rewards' do
# Uses basic_auth helper method
credentials = basic_auth('testuser','test')
get '/api/v1/rewards', nil, {'HTTP_AUTHORIZATION' => credentials }
response.code.should == '200'
response.body.should == "..."
end
# You can define this at the bottom of your spec file, or in spec_helper for convenience
def basic_auth(user, password)
ActionController::HttpAuthentication::Basic.encode_credentials user, password
end
Hope this helps someone else. Now go write some request specs!
Create a link in Javascript with the .link method
Now I don’t claim to be a Javascript expert, but I thought I knew the basics pretty well! Here’s a little-known method built into Strings that creates a link tag:
html = 'click me'.link('http://example.com')
which results in:
html = '<a href="http://example.com">click me</a>'
Wordpress Plugin – track referrers based on url GET parameters using regular expressions
First of all, all the credit and thanks to Marios Alexandrou for his wordpress plugin Social Media Alerts for Wordpress, which allows you to set up email notifications when certain query-strings are received to your wordpress site!
For example, if you wish to see when visitors come to your site from Twitter, you can specify a query string of “source=twitter”. When visitors come to your page with this parameter on the URL (ie. http://yoursite.com/?source=twitter) then this will be tracked, and you can be notified by email.
I installed this plugin but besides specifying the literal query-string, I wanted to be able to handle dynamic query-strings based on regular expressions that I could define. For example, I wanted to track all query-strings that matched “http://mysite.com?ref=..”.
This would track visits to anything where the query string matched “ref=…”. For example, “http://mysite.com?ref=twitter”, “http://mysite.com?ref=facebook”, “http://mysite.com?ref=digg”, etc.
Here’s my little bit of code to the plugin to support regular expressions :
# File: social-media-email-alerts.php
# Line: 142
# Replace the existing "get_query" function definition with this:
function get_query($qs){
global $wra_sites;
if ($qs) {
$query = explode("&",$qs);
foreach($query as $query_string){
if(is_array($wra_sites[$query_string])){
return $query_string;
}
}
# Added for regexp matching on query string
foreach($query as $query_string){
foreach($wra_sites as $key => $val){
if (preg_match($key, $query_string) > 0) {
return $key;
}
}
}
}
return false;
}
As you can see, it’s just a single foreach block that will match a query-string by regex, and return if found. Now it’s possible to add a rule for /^ref=.+/ that will alert me upon any match to this regular expression.
Ruby Multi-level Nested Hash Value
Often in my Ruby code or Rails application, I will need to find a value in a nested hash. Frequently this also comes in handy when dealing with JSON and parsing JSON to a hash. For example, I might have a hash of user information that looks like this:
user_hash = {:id => 1, :name => 'John doe', :extra => {:birthday => {:month => 11, :day => 16, :year => 1951}}}
Now, when I want to find the birthday year, I have to do something messy like this:
year = user_hash[:extra] && user_hash[:extra][:birthday] && user_hash[:extra][:birthday][:year]
How inconvenient is this?! Every level of the hash I am checking for existence of the hash-key. Here’s a helper method that I use so that I can avoid these verbose statements and get the value I want in 1 line. It adds a ‘hash_val’ method to any hash, and takes in the hash-keys as arguments. If one of the nested hash keys is missing, it will simply return nil.
# I usually define this in an initializer, so it can be used all over my app:
# Eg. Place in config/initializers/hash_val.rb
class Hash
# Fetch a nested hash value
def hash_val(*attrs)
attr_count = attrs.size
current_val = self
for i in 0..(attr_count-1)
attr_name = attrs[i]
return current_val[attr_name] if i == (attr_count-1)
return nil if current_val[attr_name].nil?
current_val = current_val[attr_name]
end
return nil
end
end
Now, getting a nested hash value is so easy!
user_hash.hash_val(:extra, :birthday, :year)
=> 1951
And, if the hash-key does not exist, it simply returns nil:
user_hash.hash_val(:extra, :trouble)
=> nil
Rails 3 – How to Rename a Project
As opposed to previous versions of Rails, Rails 3 namespaces your entire project according to your project name. As an example, notice that in your config/routes.rb file, the first line is:
ProjectName::Application.routes.draw do
...
This means that changing a project name involves changing a number of files to reference the new project name as well. Here’s a quick list of the standard files to change:
Rakefile
config.ru
config/application.rb
config/database.yml
config/environment.rb
config/environments/*.rb
config/initializers/secret_token.rb
config/initializers/session_store.rb
config/routes.rb
Besides these, it’s a good idea to also check all files in config/ and config/initializers/
If you want to be thorough, run this grep command in your project root, and you will get a list of all files that contain your old project name:
grep -Ri 'oldprojectame' * | cut -f1 -d':' | sort | uniq
