zerosum dirt(nap)

evolution through a series of accidents

zerosum dirt(nap)

Testing ActiveRecord Observers

July 25, 2009 @ 05:47 PM by nap · 2 comments

Need to unit test those pesky ActiveRecord observers you’re using? I don’t use em often, but there are times when they’re definitely useful. Fortunately, since AR::Observer leverages Ruby’s Observable module all you have to do is call MyModel.delete_observers in your test setup or before block.

ZombieSighting.delete_observers

Better yet, add the exclusions to your test or spec helper file. Then you can unit test your models comfortably in isolation, and write tests for your observers that look like this:

describe Observer
  before(:each) do
    @obs = ZombieSightingObserver.instance
    @thing = Factory.build(:zombie_sighting)
  end

  it 'should generate a new notification' do
    lambda { 
      @obs.after_create(@thing)
    }.should change(Notification, :count)
  end
end

We wouldn’t want to couple zombie sightings too tightly with notifications, after all, as that might anger them even further (zombies are known to be crazy about SRP).

2 comments

Rails Camp New England

July 21, 2009 @ 11:17 PM by nap · 2 comments

Last Friday, about 30 people descended on a large house in Bryant Pond, Maine for Rails Camp New England. Organizer Pat Allan has been running Rails Camp events in the UK and his home nation of Australia for quite some time, but this was the very first North American event (co-organized by Boston.rb’s own Brian Cardarella). Personally, I think it was a smashing success and I’m really glad I had the chance to be a part of it.

Our weekend retreat basically consisted of group hacking and pair programming, lots of lively discussions, gaming, and plenty of R&R. Frisbee was played. Food was eaten. Canoes were canoed. Urban Terror was instigated. Werewolves were slain by lakeside campfire light. Alcohol was consumed. In no particular order, of course.

Rails Camp

In addition to the ever-important extra-curriculars, we had time to work on personal projects and share with others through a series of BarCamp-style sessions. These sessions included topics as diverse as Ruby Gems, GemCutter, Internationalization, CouchDB, and RadiantCMS. There were also a number of app demos and lots of peer consulting and mentoring going on. Experience levels ranged from complete beginners to seasoned professionals, but all egos were checked at the door and everyone seemed to get along like old friends. Social games and sessions really helped people get to know one another, and keeping the event small meant that by the time you left, everyone was on a first-name basis.

I’m not sure how (cough) productive I was over the course of the weekend, but I sure had a great time, met a lot of interesting people, and learned a lot from them. If you’ve never attended anything like this I strongly encourage you to. It’s a great mix of learning and fun, and the freestyle format allows you to make of it what you want. A far better experience than any conference I’ve attended in the past year, imo, and far less costly at a mere $120 for the entire weekend, including all lodging and food.

A big thanks to Pat and Brian for all their hard work, to Thoughtbot and ZenDesk for sponsoring, and to everyone else that showed up for being full of awesome. Hopefully we’ll do another RC New England event soon. I’m thinking that a mid-winter ski lodge excursion sounds like a damn good idea… Yeh?

2 comments

TwitterAuth Integration Testing

July 13, 2009 @ 03:03 PM by nap · 4 comments

Michael Bleigh’s TwitterAuth gem is truly full of awesome. It’s a complete OAuth authentication and API access solution for building Twitter apps with Rails. It uses familiar conventions borrowed from the Restful Authentication plugin, too. If you’re building a Rails-based app and you want to allow your users to Sign in with Twitter there’s just no better way to go.

TwitterAuth

For this particular app, I’m using the dynamic duo of Cucumber and Webrat to whip up integration tests. Since I initially stumbled a little bit when thinking about how to test integrated authentication against an external source like Twitter, I thought I’d doc the solution here in case other people were having the same issue.

Ready? Let’s do it.

Setup

First, install the TwitterAuth gem and use the provided generator to whip up the appropriate facilities. You’ll need to register your Twitter application accounts too. Or you know what? Screw it. If you want to make this super easy on yourself, Mike wrote a really great Twitter app Rails template that does all the setup for you, including walking you through getting the dev accounts. It’s nice, try it out. You’ll be up and writing Twitter apps in no time.

For the rest of this I’m going to assume that you have all of that working, and have installed Cucumber too. Don’t have Cucumber? Install it using RubyGems and then just run script/generate cucumber inside your Rails app.

Authentication Feature

So let’s write a Cucumber feature to test authentication in our boilerplate Twitter template application. Put the following in features/authentication.feature:

Feature: Authentication
In order to create and edit games
As a user
I want to sign in with Twitter

  Scenario: Login via Twitter
    When I go to "the homepage"
    And I follow "Login via Twitter"
    And Twitter authorizes me
    Then I should see "Logged in as"

  Scenario: Checking login status
    Given I am signed in
    When I go to "the homepage"
    Then I should see "Logged in as"

  Scenario: Log out
    Given I am signed in
    When I go to "the homepage"
    And I follow "Log out"
    Then I should see "Login via Twitter"

Step Definitions

Next, you’ll need to write step definitions to satisfy the missing steps. Do that by creating a file called features/step_definitions/auth_steps.rb. The content of the file should define the following two steps:

Given /^I am signed in$/ do  
  visit login_path
  visit oauth_callback_path
end  

When /^Twitter authorizes me$/ do
  visit oauth_callback_path
end

Fake Style

The secret sauce here is FakeWeb. We’ll use it to fake out responses from the Twitter auth service so that your integration tests stay local (and reliable). Make sure to gem install fakeweb, and add the following to tests/environments/cucumber.rb:

config.gem "fakeweb", :version => ">= 1.2.5"

Now edit Cucumber’s features/support/env.rb file:

FakeWeb.allow_net_connect = false
FakeWeb.register_uri(:post, 'http://twitter.com/oauth/request_token', :body => 'oauth_token=fake&oauth_token_secret=fake')
FakeWeb.register_uri(:post, 'http://twitter.com/oauth/access_token', :body => 'oauth_token=fake&oauth_token_secret=fake')
FakeWeb.register_uri(:get, 'http://twitter.com/account/verify_credentials.json', :response => File.join(RAILS_ROOT, 'features', 'fixtures', 'verify_credentials.json'))

Here we’re stubbing out the interaction with Twitter auth, and responding to all outbound authorization attempts with canned data. Note that this references a fixture file, containing a sample verify_credentials API response from Twitter. You can obtain a copy using curl from the comfort of your terminal prompt (substitute your own username and password):

curl -i -u user:pass "http://twitter.com/account/verify_credentials.json" > verify_credentials.json

And We’re Done

Alright that should do it. Go ahead and run rake features. Everything should be green. And green is good. If you need to write other features that are dependent on a login requirement, you can reuse the same “Given I am signed in” step that we created earlier.

Thanks to b.kocik, whose original post on using FakeWeb to stub Twitter auth was 80% of the solution I needed here.

4 comments

Rumble Time

July 07, 2009 @ 07:41 PM by nap · 0 comments

We opened registration for the 2009 Rails Rumble yesterday. This is the third year in a row that we’re running the contest and it’s sure to be the best one yet. The build weekend is August 22nd-23rd but you need to register this week if you want a seat. If I were you, I’d go register now before it fills up ;-). Rails Rumble 2009

In other news, I’ll be presenting at the second Portsmouth Pecha-Kucha Night tomorrow, July 8th. I’ll actually be talking about the creative power of constraints, and describing our experiences organizing the Rumble will be a big part of that. If you’re in town, make sure to check it out. I’ve never done a p-k talk before but it sounds like it’s going to be a lot of fun.

0 comments