Rails 3.1 — Testing with remote XML/HTML using Nokogiri, stubs, and rspec

Stamped: 2011-05-19 00:00:00 -0400 | Show comments

So you're pulling remote data, woo!

I suppose this works in Rails 3.x, but, in order to not be a burden on the server you're grabbing the data from, it would be nice to not have to grab the data each and EVERY time you have to run the unit tests, so you have to mock Nokogiri, but how. It's quite simple, assuming you're using Nokogiri like this: doc = Nokogiri::XML(open("http://tesoriere.com?xml=1")). In your unit test, all you have to do is mock the parse function and you're done!

doc = Nokogiri::XML(open(Rails.root + 'spec/support/tesoriere.xml'))
Nokogiri::XML::Document.stub!(:parse)
Nokogiri::XML::Document.should_receive(:parse).and_return(doc)
tags: rails, bdd, mocks & stubs
recent entries
Rails — A faster way for next and previous links on a post, article, or any model
The awkward things Siri says
Node.js — Getting oAuth Up and Running Using Express.js and Mongoose
Node.js — Getting oAuth Up and Running Using Express.js, Railway.js and Mongoose
Migrating from Rails 3.1 RC4 to RC5 using Heroku's Cedar Stack (also compass, unicorn, and sendgrid)
Random Freeze Fix for GTX 460 in 10.6 (osx86)
Wasted on Steam - an analytic tool for the Steam platform
Rails 3.1 — SQL logging to STDOUT during testing (with rspec, test::unit, or cucumber)
Rails 3.1 — Using ERB/HAML/etc within a Coffeescript JS file
Rails 3.1 — 'load_missing_contant': Expected ... to define ... (LoadError)
View the entire archive of articles