Loading JSON Files Using FakeWeb in Ruby on Rails
I’m using Chris Kampmeier’s FakeWeb to set up my tests for searching with John Nunemaker’s Twitter plugin. My first setups, hitting XML, were really easy and went off without a hitch. But when I needed to start loading JSON for search results, I started getting all sorts of errors: Net::HTTPBadResponse, Can’t convert string to hash, even Can’t convert hash to string. After hours of banging my head against the wall, this is what finally worked for me:
%w[@cdwarren @bphogan].each do |keyword|
FakeWeb.register_uri(:get, "http://search.twitter.com:80/search.json?q=#{keyword}",
:string => JSON.parse(File.new("#{RAILS_ROOT}/test/files/search/#{keyword}.json").read))
end
I tried loading the file in several different ways, using :response and :file instead of :string, but they weren’t happy with what I was doing either.
Oh, and for the record, this is how I’m loading the XML files. Many thanks to Brian Hogan for getting me going on this part.
%w[cdwarren bphogan].each do |screen_name|
FakeWeb.register_uri(:get, "http://twitter.com:80/users/show/#{screen_name}.xml",
:string => REXML::Document.new(File.new("#{RAILS_ROOT}/test/files/profile/#{screen_name}.xml")))
end
Oh, and don’t forget to require 'json' if you’re going to use JSON.parse!
