Skip to content

Instantly share code, notes, and snippets.

@djanowski
Created January 7, 2009 17:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save djanowski/44344 to your computer and use it in GitHub Desktop.
Save djanowski/44344 to your computer and use it in GitHub Desktop.
Testing Facebook interaction with Facebooker
# DISCLAIMER: this is just a hack, not even tested.
# I use this for testing interaction with Facebook.
# Basically there are a bunch of fixture XMLs that
# represent the response from Facebook.
# Oh, make sure you do this somewhere, probably in
# a setup/before block:
#
# Facebooker::Session.current = Facebooker::MockSession.create
#
# (You might need to stub session[:facebook_session] too.)
require 'digest/md5'
module Facebooker
class MockService < Service
def post(params)
method = params[:method]
params.delete(:v)
params.delete(:method)
params.delete(:api_key)
params.delete(:call_id)
params.delete(:sig)
filename = get_fixture_name(params)
path = get_fixture_path(method, filename)
begin
begin
response = Parser.parse(method, File.read(path))
rescue Errno::ENAMETOOLONG
tries = 0
md5_alternative = nil
begin
md5_path = get_hashed_fixture_path(method, md5_alternative || filename)
response = Parser.parse(method, File.read(md5_path))
if md5_alternative
puts "It looks like you need to rename this file due to changes in Facebooker's user fields."
$stderr.puts "git mv #{md5_path} #{get_hashed_fixture_path(method, filename)}"
end
rescue Errno::ENOENT => e
fields ||= params[:fields].split(',') if params[:fields]
tries += 1
raise if fields.nil? || tries > Facebooker::User::FIELDS.size
fields.delete(Facebooker::User::FIELDS[-tries].to_s)
md5_alternative = get_fixture_name(params.merge(:fields => fields.join(',')))
retry
end
end
rescue Errno::ENOENT => e
e.message << "\n(Non-hashed path is #{path})" if md5_path
e.message << "\nFacebook API Reference: http://wiki.developers.facebook.com/index.php/#{method.sub(/^facebook\./, '')}#Example_Return_XML"
raise e
end
response
end
def kind_of?(klass)
if klass == Facebooker::Session
true
else
super
end
end
private
def get_fixture_path(method, filename)
File.join('.', 'test', 'fixtures', 'facebook', method, "#{filename}.xml")
end
def get_hashed_fixture_path(method, filename)
get_fixture_path(method, Digest::MD5.hexdigest(filename))
end
def get_fixture_name(params)
params.map {|*args| args.join('=') }.sort.join('&')
end
end
class MockSession < Session
def secured?
true
end
def secure!
@uid = 1
true
end
def service
@service ||= MockService.new(Facebooker.api_server_base, Facebooker.api_rest_path, @api_key)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment