PageRenderTime 74ms CodeModel.GetById 36ms RepoModel.GetById 0ms app.codeStats 1ms

/test/facebooker/rails_integration_test.rb

http://github.com/mmangino/facebooker
Ruby | 1543 lines | 1305 code | 232 blank | 6 comment | 12 complexity | 2e13bd722675080c195572248a858719 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. require File.expand_path(File.dirname(__FILE__) + '/../rails_test_helper')
  2. module FBConnectTestHelpers
  3. def setup_fb_connect_cookies(params=cookie_hash_for_auth)
  4. params.each {|k,v| @request.cookies[ENV['FACEBOOK_API_KEY']+k] = CGI::Cookie.new(ENV['FACEBOOK_API_KEY']+k,v).first}
  5. end
  6. def expired_cookie_hash_for_auth
  7. {"_ss" => "not_used", "_session_key"=> "whatever", "_user"=>"77777", "_expires"=>"#{1.day.ago.to_i}"}
  8. end
  9. def cookie_hash_for_auth
  10. {"_ss" => "not_used", "_session_key"=> "whatever", "_user"=>"77777", "_expires"=>"#{1.day.from_now.to_i}"}
  11. end
  12. end
  13. class NoisyController < ActionController::Base
  14. include Facebooker::Rails::Controller
  15. def rescue_action(e) raise e end
  16. end
  17. class ControllerWhichRequiresExtendedPermissions< NoisyController
  18. ensure_authenticated_to_facebook
  19. before_filter :ensure_has_status_update
  20. before_filter :ensure_has_photo_upload
  21. before_filter :ensure_has_video_upload
  22. before_filter :ensure_has_create_listing
  23. before_filter :ensure_has_create_event
  24. def index
  25. render :text => 'score!'
  26. end
  27. end
  28. class FBConnectController < NoisyController
  29. before_filter :create_facebook_session
  30. def index
  31. render :text => 'score!'
  32. end
  33. end
  34. class FBConnectControllerProxy < NoisyController
  35. before_filter :create_facebook_session_with_secret
  36. def index
  37. render :text => 'score!'
  38. end
  39. end
  40. class ControllerWhichRequiresFacebookAuthentication < NoisyController
  41. ensure_authenticated_to_facebook
  42. def index
  43. render :text => 'score!'
  44. end
  45. def link_test
  46. options = {}
  47. options[:canvas] = true if params[:canvas] == true
  48. options[:canvas] = false if params[:canvas] == false
  49. render :text=>url_for(options)
  50. end
  51. def named_route_test
  52. render :text=>comments_url()
  53. end
  54. def image_test
  55. render :inline=>"<%=image_tag 'image.png'%>"
  56. end
  57. def fb_params_test
  58. render :text=>facebook_params['user']
  59. end
  60. def publisher_test
  61. if wants_interface?
  62. render :text=>"interface"
  63. else
  64. render :text=>"not interface"
  65. end
  66. end
  67. def publisher_test_interface
  68. render_publisher_interface("This is a test",false,true)
  69. end
  70. def publisher_test_response
  71. ua=Facebooker::Rails::Publisher::UserAction.new
  72. ua.data = {:params=>true}
  73. ua.template_name = "template_name"
  74. ua.template_id = 1234
  75. render_publisher_response(ua)
  76. end
  77. def publisher_test_error
  78. render_publisher_error("Title","Body")
  79. end
  80. end
  81. class ControllerWhichRequiresApplicationInstallation < NoisyController
  82. ensure_application_is_installed_by_facebook_user
  83. def index
  84. render :text => 'installed!'
  85. end
  86. end
  87. class FacebookController < ActionController::Base
  88. def index
  89. end
  90. end
  91. class PlainOldRailsController < ActionController::Base
  92. def index
  93. end
  94. def link_test
  95. options = {}
  96. options[:canvas] = true if params[:canvas] == true
  97. options[:canvas] = false if params[:canvas] == false
  98. render :text => url_for(options)
  99. end
  100. def named_route_test
  101. render :text=>comments_url()
  102. end
  103. def canvas_false_test
  104. render :text=>comments_url(:canvas=>false)
  105. end
  106. def canvas_true_test
  107. render :text=>comments_url(:canvas=>true)
  108. end
  109. end
  110. # you can't use asset_recognize, because it can't pass parameters in to the requests
  111. class UrlRecognitionTests < Test::Unit::TestCase
  112. def test_detects_in_canvas
  113. if Rails.version < '2.3'
  114. request = ActionController::TestRequest.new({"fb_sig_in_canvas"=>"1"}, {}, nil)
  115. else
  116. request = ActionController::TestRequest.new
  117. request.query_parameters[:fb_sig_in_canvas] = "1"
  118. end
  119. request.path = "/"
  120. ActionController::Routing::Routes.recognize(request)
  121. assert_equal({"controller"=>"facebook","action"=>"index"},request.path_parameters)
  122. end
  123. def test_routes_when_not_in_canvas
  124. if Rails.version < '2.3'
  125. request = ActionController::TestRequest.new({}, {}, nil)
  126. else
  127. request = ActionController::TestRequest.new
  128. end
  129. request.path = "/"
  130. ActionController::Routing::Routes.recognize(request)
  131. assert_equal({"controller"=>"plain_old_rails","action"=>"index"},request.path_parameters)
  132. end
  133. end
  134. class RailsIntegrationTestForFBConnect < Test::Unit::TestCase
  135. include FBConnectTestHelpers
  136. def setup
  137. Facebooker.apply_configuration({
  138. 'api_key' => '1234567',
  139. 'canvas_page_name' => 'facebook_app_name',
  140. 'secret_key' => '7654321' })
  141. @controller = FBConnectController.new
  142. @request = ActionController::TestRequest.new
  143. @response = ActionController::TestResponse.new
  144. @controller.stubs(:verify_signature).returns(true)
  145. end
  146. def test_doesnt_set_cookie_but_facebook_session_is_available
  147. setup_fb_connect_cookies
  148. get :index
  149. assert_not_nil @controller.facebook_session
  150. assert_nil @response.cookies[:facebook_session]
  151. end
  152. end
  153. class RailsIntegrationTestForNonFacebookControllers < Test::Unit::TestCase
  154. def setup
  155. Facebooker.apply_configuration({
  156. 'api_key' => '1234567',
  157. 'canvas_page_name' => 'facebook_app_name',
  158. 'secret_key' => '7654321' })
  159. @controller = PlainOldRailsController.new
  160. @request = ActionController::TestRequest.new
  161. @response = ActionController::TestResponse.new
  162. end
  163. def test_url_for_links_to_callback_if_canvas_is_false_and_in_canvas
  164. get :link_test
  165. assert_match(/test.host/, @response.body)
  166. end
  167. def test_named_route_doesnt_include_canvas_path_when_not_in_canvas
  168. get :named_route_test
  169. assert_equal "http://test.host/comments",@response.body
  170. end
  171. def test_named_route_includes_canvas_path_when_in_canvas
  172. get :named_route_test, facebook_params
  173. assert_equal "http://apps.facebook.com/facebook_app_name/comments",@response.body
  174. end
  175. def test_named_route_doesnt_include_canvas_path_when_in_canvas_with_canvas_equals_false
  176. get :canvas_false_test, facebook_params
  177. assert_equal "http://test.host/comments",@response.body
  178. end
  179. def test_named_route_does_include_canvas_path_when_not_in_canvas_with_canvas_equals_true
  180. get :canvas_true_test
  181. assert_equal "http://apps.facebook.com/facebook_app_name/comments",@response.body
  182. end
  183. end
  184. class RailsIntegrationTestForExtendedPermissions < Test::Unit::TestCase
  185. def setup
  186. Facebooker.apply_configuration({
  187. 'api_key' => '1234567',
  188. 'secret_key' => '7654321' })
  189. @controller = ControllerWhichRequiresExtendedPermissions.new
  190. @request = ActionController::TestRequest.new
  191. @response = ActionController::TestResponse.new
  192. @controller.stubs(:verify_signature).returns(true)
  193. end
  194. def test_redirects_without_set_status
  195. post :index, facebook_params
  196. assert_response :success
  197. assert_equal("<fb:redirect url=\"http://www.facebook.com/authorize.php?api_key=1234567&v=1.0&ext_perm=status_update\" />", @response.body)
  198. end
  199. def test_redirects_without_photo_upload
  200. post :index, facebook_params(:fb_sig_ext_perms=>"status_update,create_event")
  201. assert_response :success
  202. assert_equal("<fb:redirect url=\"http://www.facebook.com/authorize.php?api_key=1234567&v=1.0&ext_perm=photo_upload\" />", @response.body)
  203. end
  204. def test_redirects_without_video_upload
  205. post :index, facebook_params(:fb_sig_ext_perms=>"status_update,photo_upload,create_event")
  206. assert_response :success
  207. assert_equal("<fb:redirect url=\"http://www.facebook.com/authorize.php?api_key=1234567&v=1.0&ext_perm=video_upload\" />", @response.body)
  208. end
  209. def test_redirects_without_create_listing
  210. post :index, facebook_params(:fb_sig_ext_perms=>"status_update,photo_upload,video_upload,create_event")
  211. assert_response :success
  212. assert_equal("<fb:redirect url=\"http://www.facebook.com/authorize.php?api_key=1234567&v=1.0&ext_perm=create_listing\" />", @response.body)
  213. end
  214. def test_redirects_without_create_event
  215. post :index, facebook_params(:fb_sig_ext_perms=>"status_update,photo_upload,create_listing,video_upload")
  216. assert_response :success
  217. assert_equal("<fb:redirect url=\"http://www.facebook.com/authorize.php?api_key=1234567&v=1.0&ext_perm=create_event\" />", @response.body)
  218. end
  219. def test_renders_with_permission
  220. post :index, facebook_params(:fb_sig_ext_perms=>"status_update,photo_upload,create_listing,video_upload,create_event")
  221. assert_response :success
  222. assert_equal("score!", @response.body)
  223. end
  224. end
  225. class RailsIntegrationTestForApplicationInstallation < Test::Unit::TestCase
  226. def setup
  227. Facebooker.apply_configuration({
  228. 'api_key' => '1234567',
  229. 'secret_key' => '7654321' })
  230. @controller = ControllerWhichRequiresApplicationInstallation.new
  231. @request = ActionController::TestRequest.new
  232. @response = ActionController::TestResponse.new
  233. @controller.stubs(:verify_signature).returns(true)
  234. end
  235. def test_if_controller_requires_application_installation_unauthenticated_requests_will_redirect_to_install_page
  236. get :index
  237. assert_response :redirect
  238. assert_equal("http://www.facebook.com/install.php?api_key=1234567&v=1.0&next=http%3A%2F%2Ftest.host%2Frequire_install", @response.headers['Location'])
  239. end
  240. def test_if_controller_requires_application_installation_authenticated_requests_without_installation_will_redirect_to_install_page
  241. get :index, facebook_params(:fb_sig_added => nil)
  242. assert_response :success
  243. assert(@response.body =~ /fb:redirect/)
  244. end
  245. def test_if_controller_requires_application_installation_authenticated_requests_with_installation_will_render
  246. get :index, facebook_params('fb_sig_added' => "1")
  247. assert_response :success
  248. assert_equal("installed!", @response.body)
  249. end
  250. end
  251. class RailsIntegrationTest < Test::Unit::TestCase
  252. include FBConnectTestHelpers
  253. def setup
  254. Facebooker.apply_configuration({
  255. 'api_key' => '1234567',
  256. 'canvas_page_name' => 'root',
  257. 'secret_key' => '7654321',
  258. 'set_asset_host_to_callback_url' => true,
  259. 'callback_url' => "http://root.example.com" })
  260. @controller = ControllerWhichRequiresFacebookAuthentication.new
  261. @request = ActionController::TestRequest.new
  262. @response = ActionController::TestResponse.new
  263. @controller.stubs(:verify_signature).returns(true)
  264. end
  265. def test_named_route_includes_new_canvas_path_when_in_new_canvas
  266. get :named_route_test, facebook_params("fb_sig_in_new_facebook"=>"1")
  267. assert_equal "http://apps.facebook.com/root/comments",@response.body
  268. end
  269. def test_if_controller_requires_facebook_authentication_unauthenticated_requests_will_redirect
  270. get :index
  271. assert_response :redirect
  272. assert_equal("http://www.facebook.com/login.php?api_key=1234567&v=1.0&next=http%3A%2F%2Ftest.host%2Frequire_auth", @response.headers['Location'])
  273. end
  274. def test_facebook_params_are_parsed_into_a_separate_hash
  275. get :index, facebook_params(:fb_sig_user => '9')
  276. assert_not_nil @controller.facebook_params['time']
  277. end
  278. def test_facebook_params_convert_in_canvas_to_boolean
  279. get :index, facebook_params
  280. assert_equal(true, @controller.facebook_params['in_canvas'])
  281. end
  282. def test_facebook_params_convert_added_to_boolean_false
  283. get :index, facebook_params(:fb_sig_added => '0')
  284. assert_equal(false, @controller.facebook_params['added'])
  285. end
  286. def test_facebook_params_convert_added_to_boolean_true
  287. get :index, facebook_params('fb_sig_added' => "1")
  288. assert_equal(true, @controller.facebook_params['added'])
  289. end
  290. def test_facebook_params_convert_added_to_boolean_false_when_already_false
  291. get :index, facebook_params('fb_sig_added' => false)
  292. assert_equal(false, @controller.facebook_params['added'])
  293. end
  294. def test_facebook_params_convert_added_to_boolean_true_when_already_true
  295. get :index, facebook_params('fb_sig_added' => true)
  296. assert_equal(true, @controller.facebook_params['added'])
  297. end
  298. def test_facebook_params_convert_expirey_into_nil
  299. get :index, facebook_params(:fb_sig_expires => '0')
  300. assert_nil(@controller.facebook_params['expires'])
  301. end
  302. def test_facebook_params_convert_expirey_into_time
  303. get :index, facebook_params(:fb_sig_expires => 5.minutes.from_now.to_f)
  304. assert_instance_of Time, @controller.facebook_params['expires']
  305. end
  306. def test_facebook_params_convert_friend_list_to_parsed_array_of_friend_ids
  307. get :index, facebook_params(:fb_sig_friends => '1,2,3,4,5')
  308. assert_kind_of(Array, @controller.facebook_params['friends'])
  309. assert_equal(5, @controller.facebook_params['friends'].size)
  310. end
  311. def test_session_can_be_resecured_from_facebook_params
  312. get :index, facebook_params(:fb_sig_user => 10)
  313. assert_equal(10, @controller.facebook_session.user.id)
  314. end
  315. def test_existing_secured_session_is_used_if_available
  316. session = Facebooker::Session.create(Facebooker::Session.api_key, Facebooker::Session.secret_key)
  317. session.secure_with!("session_key", "111", Time.now.to_i + 60)
  318. get :index, facebook_params(:fb_sig_session_key => 'session_key', :fb_sig_user => '987'), {:facebook_session => session}
  319. assert_equal(111, @controller.facebook_session.user.id)
  320. end
  321. def test_facebook_params_used_if_existing_secured_session_key_does_not_match
  322. session = Facebooker::Session.create(Facebooker::Session.api_key, Facebooker::Session.secret_key)
  323. session.secure_with!("different session key", "111", Time.now.to_i + 60)
  324. get :index, facebook_params(:fb_sig_session_key => '', :fb_sig_user => '123'), {:facebook_session => session}
  325. assert_equal(123, @controller.facebook_session.user.id)
  326. end
  327. def test_existing_secured_session_is_NOT_used_if_available_and_facebook_params_session_key_is_nil_and_in_canvas
  328. session = Facebooker::Session.create(Facebooker::Session.api_key, Facebooker::Session.secret_key)
  329. session.secure_with!("session_key", "111", Time.now.to_i + 60)
  330. session.secure_with!("a session key", "1111111", Time.now.to_i + 60)
  331. get :index, facebook_params(:fb_sig_session_key => '', :fb_sig_user => '987'), {:facebook_session => session}
  332. assert_equal(987, @controller.facebook_session.user.id)
  333. end
  334. def test_existing_secured_session_IS_used_if_available_and_facebook_params_session_key_is_nil_and_NOT_in_canvas
  335. @contoller = PlainOldRailsController.new
  336. session = Facebooker::Session.create(ENV['FACEBOOK_API_KEY'], ENV['FACEBOOK_SECRET_KEY'])
  337. session.secure_with!("a session key", "1111111", Time.now.to_i + 60)
  338. get :index,{}, {:facebook_session => session}
  339. assert_equal(1111111, @controller.facebook_session.user.id)
  340. end
  341. def test_session_can_be_secured_with_secret
  342. @controller = FBConnectControllerProxy.new
  343. auth_token = 'ohaiauthtokenhere111'
  344. modified_params = facebook_params
  345. modified_params.delete('fb_sig_session_key')
  346. modified_params['auth_token'] = auth_token
  347. modified_params['generate_session_secret'] = true
  348. session_mock = flexmock(session = Facebooker::Session.create(ENV['FACEBOOK_API_KEY'], ENV['FACEBOOK_SECRET_KEY']))
  349. session_params = { 'session_key' => '123', 'uid' => '321' }
  350. session_mock.should_receive(:post).with('facebook.auth.getSession', :auth_token => auth_token, :generate_session_secret => "1").once.and_return(session_params).ordered
  351. flexmock(@controller).should_receive(:new_facebook_session).once.and_return(session).ordered
  352. get :index, modified_params
  353. end
  354. def test_session_can_be_secured_with_auth_token
  355. auth_token = 'ohaiauthtokenhere111'
  356. modified_params = facebook_params
  357. modified_params.delete('fb_sig_session_key')
  358. modified_params['auth_token'] = auth_token
  359. session_mock = flexmock(session = Facebooker::Session.create(ENV['FACEBOOK_API_KEY'], ENV['FACEBOOK_SECRET_KEY']))
  360. session_params = { 'session_key' => '123', 'uid' => '321' }
  361. session_mock.should_receive(:post).with('facebook.auth.getSession', :auth_token => auth_token, :generate_session_secret => "0").once.and_return(session_params).ordered
  362. flexmock(@controller).should_receive(:new_facebook_session).once.and_return(session).ordered
  363. get :index, modified_params
  364. end
  365. def test_session_secured_with_auth_token_if_cookies_expired
  366. auth_token = 'ohaiauthtokenhere111'
  367. modified_params = facebook_params
  368. modified_params.delete('fb_sig_session_key')
  369. modified_params['auth_token'] = auth_token
  370. session_mock = flexmock(session = Facebooker::Session.create(ENV['FACEBOOK_API_KEY'], ENV['FACEBOOK_SECRET_KEY']))
  371. session_params = { 'session_key' => '123', 'uid' => '321' }
  372. session_mock.should_receive(:post).with('facebook.auth.getSession', :auth_token => auth_token, :generate_session_secret => "0").once.and_return(session_params).ordered
  373. flexmock(@controller).should_receive(:new_facebook_session).once.and_return(session).ordered
  374. setup_fb_connect_cookies(expired_cookie_hash_for_auth)
  375. get :index, modified_params
  376. assert_equal(321, @controller.facebook_session.user.id)
  377. end
  378. def test_session_can_be_secured_with_cookies
  379. setup_fb_connect_cookies
  380. get :index
  381. assert_equal(77777, @controller.facebook_session.user.id)
  382. end
  383. def test_session_does_NOT_secure_with_expired_cookies
  384. setup_fb_connect_cookies(expired_cookie_hash_for_auth)
  385. get :index
  386. assert_nil(@controller.facebook_session)
  387. end
  388. def test_user_friends_can_be_populated_from_facebook_params_if_available
  389. get :index, facebook_params(:fb_sig_friends => '1,2,3,4')
  390. friends = @controller.facebook_session.user.friends
  391. assert_not_nil(friends)
  392. assert_equal(4, friends.size)
  393. end
  394. def test_fbml_redirect_tag_handles_hash_parameters_correctly
  395. get :index, facebook_params
  396. assert_equal "<fb:redirect url=\"http://apps.facebook.com/root/require_auth\" />", @controller.send(:fbml_redirect_tag, :action => :index,:canvas=>true)
  397. end
  398. def test_redirect_to_renders_fbml_redirect_tag_if_request_is_for_a_facebook_canvas
  399. get :index, facebook_params(:fb_sig_user => nil)
  400. assert_response :success
  401. assert @response.body =~ /fb:redirect/
  402. end
  403. def test_redirect_to_renders_javascript_redirect_if_request_is_for_a_facebook_iframe
  404. get :index, facebook_params(:fb_sig_user => nil, :fb_sig_in_iframe => 1)
  405. assert_response :success
  406. assert_match "javascript", @response.body
  407. assert_match "http-equiv", @response.body
  408. assert_match "http://www.facebook.com/login.php?api_key=1234567&amp;v=1.0", @response.body
  409. end
  410. def test_url_for_links_to_canvas_if_canvas_is_true_and_not_in_canvas
  411. get :link_test, facebook_params(:fb_sig_in_canvas=>0,:canvas=>true)
  412. assert_match(/apps.facebook.com/, @response.body)
  413. end
  414. def test_includes_relative_url_root_when_linked_to_canvas
  415. get :link_test,facebook_params(:fb_sig_in_canvas=>0,:canvas=>true)
  416. assert_match(/root/,@response.body)
  417. end
  418. def test_url_for_links_to_callback_if_canvas_is_false_and_in_canvas
  419. get :link_test,facebook_params(:fb_sig_in_canvas=>0,:canvas=>false)
  420. assert_match(/test.host/,@response.body)
  421. end
  422. def test_url_for_doesnt_include_url_root_when_not_linked_to_canvas
  423. get :link_test,facebook_params(:fb_sig_in_canvas=>0,:canvas=>false)
  424. assert !@response.body.match(/root/)
  425. end
  426. def test_url_for_links_to_canvas_if_fb_sig_is_ajax_is_true_and_fb_sig_in_canvas_is_not_true
  427. # Normal fb ajax calls have no fb_sig_canvas_param but we must explicitly set it to 0 because it is set to 1 in default_facebook_parameters in test helpers
  428. get :link_test, facebook_params(:fb_sig_is_ajax=>1, :fb_sig_in_canvas=>0)
  429. assert_match(/apps.facebook.com/, @response.body)
  430. end
  431. def test_default_url_omits_fb_params
  432. get :index,facebook_params(:fb_sig_friends=>"overwriteme",:get_param=>"yes")
  433. assert_equal "http://apps.facebook.com/root/require_auth?get_param=yes", @controller.send(:default_after_facebook_login_url)
  434. end
  435. def test_url_for_links_to_canvas_if_canvas_is_not_set
  436. get :link_test,facebook_params
  437. assert_match(/apps.facebook.com/,@response.body)
  438. end
  439. def test_image_tag
  440. get :image_test, facebook_params
  441. assert_equal "<img alt=\"Image\" src=\"http://root.example.com/images/image.png\" />",@response.body
  442. end
  443. def test_wants_interface_is_available_and_detects_method
  444. get :publisher_test, facebook_params(:method=>"publisher_getInterface")
  445. assert_equal "interface",@response.body
  446. end
  447. def test_wants_interface_is_available_and_detects_not_interface
  448. get :publisher_test, facebook_params(:method=>"publisher_getFeedStory")
  449. assert_equal "not interface",@response.body
  450. end
  451. def test_publisher_test_error
  452. get :publisher_test_error, facebook_params
  453. assert_equal Facebooker.json_decode("{\"errorCode\": 1, \"errorTitle\": \"Title\", \"errorMessage\": \"Body\"}"), Facebooker.json_decode(@response.body)
  454. end
  455. def test_publisher_test_interface
  456. get :publisher_test_interface, facebook_params
  457. assert_equal Facebooker.json_decode("{\"method\": \"publisher_getInterface\", \"content\": {\"fbml\": \"This is a test\", \"publishEnabled\": false, \"commentEnabled\": true}}"), Facebooker.json_decode(@response.body)
  458. end
  459. def test_publisher_test_reponse
  460. get :publisher_test_response, facebook_params
  461. assert_equal Facebooker.json_decode("{\"method\": \"publisher_getFeedStory\", \"content\": {\"feed\": {\"template_data\": {\"params\": true}, \"template_id\": 1234}}}"), Facebooker.json_decode(@response.body)
  462. end
  463. private
  464. def expired_cookie_hash_for_auth
  465. {"_ss" => "not_used", "_session_key"=> "whatever", "_user"=>"77777", "_expires"=>"#{1.day.ago.to_i}"}
  466. end
  467. def cookie_hash_for_auth
  468. {"_ss" => "not_used", "_session_key"=> "whatever", "_user"=>"77777", "_expires"=>"#{1.day.from_now.to_i}"}
  469. end
  470. end
  471. class RailsSignatureTest < Test::Unit::TestCase
  472. def setup
  473. Facebooker.apply_configuration({
  474. 'api_key' => '1234567',
  475. 'canvas_page_name' => 'root',
  476. 'secret_key' => '7654321' })
  477. @controller = ControllerWhichRequiresFacebookAuthentication.new
  478. @request = ActionController::TestRequest.new
  479. @response = ActionController::TestResponse.new
  480. end
  481. if Rails.version < '2.3'
  482. def test_should_raise_on_bad_sig
  483. begin
  484. get :fb_params_test, facebook_params.merge('fb_sig' => 'incorrect')
  485. fail "No IncorrectSignature raised"
  486. rescue Facebooker::Session::IncorrectSignature=>e
  487. end
  488. end
  489. def test_valid_signature
  490. @controller.expects(:earliest_valid_session).returns(Time.at(1186588275.5988)-1)
  491. get :fb_params_test, facebook_params
  492. end
  493. end
  494. def test_should_raise_too_old_for_replayed_session
  495. begin
  496. get :fb_params_test, facebook_params('fb_sig_time' => Time.now.to_i - 49.hours)
  497. fail "No SignatureTooOld raised"
  498. rescue Facebooker::Session::SignatureTooOld=>e
  499. end
  500. end
  501. end
  502. class RailsHelperTest < Test::Unit::TestCase
  503. class HelperClass
  504. include ActionView::Helpers::TextHelper
  505. include ActionView::Helpers::CaptureHelper
  506. include ActionView::Helpers::TagHelper
  507. include ActionView::Helpers::AssetTagHelper
  508. include ActionView::Helpers::JavaScriptHelper
  509. include Facebooker::Rails::Helpers
  510. attr_accessor :flash, :output_buffer
  511. def initialize
  512. @flash={}
  513. @template = self
  514. @content_for_test_param="Test Param"
  515. @output_buffer = ""
  516. end
  517. #used for stubbing out the form builder
  518. def url_for(arg)
  519. arg
  520. end
  521. def request
  522. ActionController::TestRequest.new
  523. end
  524. def fields_for(*args)
  525. ""
  526. end
  527. end
  528. # used for capturing the contents of some of the helper tests
  529. # this duplicates the rails template system
  530. attr_accessor :_erbout
  531. def setup
  532. Facebooker.apply_configuration({
  533. 'api_key' => '1234567',
  534. 'canvas_page_name' => 'facebook',
  535. 'secret_key' => '7654321' })
  536. @_erbout = ""
  537. @h = HelperClass.new
  538. #use an asset path where the canvas path equals the hostname to make sure we handle that case right
  539. ActionController::Base.asset_host='http://facebook.host.com'
  540. end
  541. def test_fb_profile_pic
  542. assert_equal "<fb:profile-pic uid=\"1234\"></fb:profile-pic>", @h.fb_profile_pic("1234")
  543. end
  544. def test_fb_profile_pic_with_valid_size
  545. assert_equal "<fb:profile-pic size=\"small\" uid=\"1234\"></fb:profile-pic>", @h.fb_profile_pic("1234", :size => :small)
  546. end
  547. def test_fb_profile_pic_with_width_and_height
  548. assert_equal "<fb:profile-pic height=\"200\" uid=\"1234\" width=\"100\"></fb:profile-pic>", @h.fb_profile_pic("1234", :width => 100, :height => 200)
  549. end
  550. def test_fb_profile_pic_with_invalid_size
  551. assert_raises(ArgumentError) {@h.fb_profile_pic("1234", :size => :mediumm)}
  552. end
  553. def test_fb_photo
  554. assert_equal "<fb:photo pid=\"1234\"></fb:photo>",@h.fb_photo("1234")
  555. end
  556. def test_fb_photo_with_object_responding_to_photo_id
  557. photo = flexmock("photo", :photo_id => "5678")
  558. assert_equal "<fb:photo pid=\"5678\"></fb:photo>", @h.fb_photo(photo)
  559. end
  560. def test_fb_photo_with_invalid_size
  561. assert_raises(ArgumentError) {@h.fb_photo("1234", :size => :medium)}
  562. end
  563. def test_fb_photo_with_invalid_size_value
  564. assert_raises(ArgumentError) {@h.fb_photo("1234", :size => :mediumm)}
  565. end
  566. def test_fb_photo_with_invalid_align_value
  567. assert_raises(ArgumentError) {@h.fb_photo("1234", :align => :rightt)}
  568. end
  569. def test_fb_photo_with_valid_align_value
  570. assert_equal "<fb:photo align=\"right\" pid=\"1234\"></fb:photo>",@h.fb_photo("1234", :align => :right)
  571. end
  572. def test_fb_photo_with_class
  573. assert_equal "<fb:photo class=\"picky\" pid=\"1234\"></fb:photo>",@h.fb_photo("1234", :class => :picky)
  574. end
  575. def test_fb_photo_with_style
  576. assert_equal "<fb:photo pid=\"1234\" style=\"some=css;put=here;\"></fb:photo>",@h.fb_photo("1234", :style => "some=css;put=here;")
  577. end
  578. def test_fb_prompt_permission_valid_no_callback
  579. assert_equal "<fb:prompt-permission perms=\"email\">Can I email you?</fb:prompt-permission>",@h.fb_prompt_permission("email","Can I email you?")
  580. end
  581. def test_fb_prompt_permission_valid_with_callback
  582. assert_equal "<fb:prompt-permission next_fbjs=\"do_stuff()\" perms=\"email\">a message</fb:prompt-permission>",@h.fb_prompt_permission("email","a message","do_stuff()")
  583. end
  584. def test_fb_prompt_permission_invalid_option
  585. assert_raises(ArgumentError) {@h.fb_prompt_permission("invliad", "a message")}
  586. end
  587. def test_fb_prompt_permissions_valid_no_callback
  588. assert_equal "<fb:prompt-permission perms=\"publish_stream,read_stream\">Can I read and write your streams?</fb:prompt-permission>",
  589. @h.fb_prompt_permissions(['publish_stream', 'read_stream'],"Can I read and write your streams?")
  590. end
  591. def test_fb_prompt_permissions_valid_with_callback
  592. assert_equal "<fb:prompt-permission next_fbjs=\"do_stuff()\" perms=\"publish_stream,read_stream\">Can I read and write your streams?</fb:prompt-permission>",
  593. @h.fb_prompt_permissions(['publish_stream', 'read_stream'],"Can I read and write your streams?", "do_stuff()")
  594. end
  595. def test_fb_prompt_permissions_invalid_option
  596. assert_raises(ArgumentError) {@h.fb_prompt_permissions(["invliad", "read_stream"], "a message")}
  597. end
  598. def test_fb_add_profile_section
  599. assert_equal "<fb:add-section-button section=\"profile\" />",@h.fb_add_profile_section
  600. end
  601. def test_fb_add_info_section
  602. assert_equal "<fb:add-section-button section=\"info\" />",@h.fb_add_info_section
  603. end
  604. def test_fb_application_name
  605. assert_equal "<fb:application-name />", @h.fb_application_name
  606. end
  607. def test_fb_application_name_with_linked_false
  608. assert_equal '<fb:application-name linked="false" />', @h.fb_application_name( :linked => false )
  609. end
  610. def test_fb_name_with_invalid_key_size
  611. assert_raises(ArgumentError) {@h.fb_name(1234, :sizee => false)}
  612. end
  613. def test_fb_name
  614. assert_equal "<fb:name uid=\"1234\"></fb:name>",@h.fb_name("1234")
  615. end
  616. def test_fb_name_with_transformed_key
  617. assert_equal "<fb:name uid=\"1234\" useyou=\"true\"></fb:name>", @h.fb_name(1234, :use_you => true)
  618. end
  619. def test_fb_name_with_user_responding_to_facebook_id
  620. user = flexmock("user", :facebook_id => "5678")
  621. assert_equal "<fb:name uid=\"5678\"></fb:name>", @h.fb_name(user)
  622. end
  623. def test_fb_name_with_invalid_key_linkd
  624. assert_raises(ArgumentError) {@h.fb_name(1234, :linkd => false)}
  625. end
  626. def test_fb_tabs
  627. assert_equal "<fb:tabs></fb:tabs>", @h.fb_tabs{}
  628. end
  629. def test_fb_tab_item
  630. assert_equal "<fb:tab-item href=\"http://www.google.com\" title=\"Google\" />", @h.fb_tab_item("Google", "http://www.google.com")
  631. end
  632. def test_fb_tab_item_raises_exception_for_invalid_option
  633. assert_raises(ArgumentError) {@h.fb_tab_item("Google", "http://www.google.com", :alignn => :right)}
  634. end
  635. def test_fb_tab_item_raises_exception_for_invalid_align_value
  636. assert_raises(ArgumentError) {@h.fb_tab_item("Google", "http://www.google.com", :align => :rightt)}
  637. end
  638. def test_fb_req_choice
  639. assert_equal "<fb:req-choice label=\"label\" url=\"url\" />", @h.fb_req_choice("label","url")
  640. end
  641. def test_fb_multi_friend_selector
  642. assert_equal "<fb:multi-friend-selector actiontext=\"This is a message\" max=\"20\" showborder=\"false\" />", @h.fb_multi_friend_selector("This is a message")
  643. end
  644. def test_fb_multi_friend_selector_with_options
  645. assert_equal "<fb:multi-friend-selector actiontext=\"This is a message\" exclude_ids=\"1,2\" max=\"20\" showborder=\"false\" />", @h.fb_multi_friend_selector("This is a message",:exclude_ids=>"1,2")
  646. end
  647. def test_fb_title
  648. assert_equal "<fb:title>This is the canvas page window title</fb:title>", @h.fb_title("This is the canvas page window title")
  649. end
  650. def test_fb_google_analytics
  651. assert_equal "<fb:google-analytics uacct=\"UA-9999999-99\" />", @h.fb_google_analytics("UA-9999999-99")
  652. end
  653. def test_fb_if_is_user_with_single_object
  654. user = flexmock("user", :facebook_id => "5678")
  655. assert_equal "<fb:if-is-user uid=\"5678\"></fb:if-is-user>", @h.fb_if_is_user(user){}
  656. end
  657. def test_fb_if_is_user_with_array
  658. user1 = flexmock("user", :facebook_id => "5678")
  659. user2 = flexmock("user", :facebook_id => "1234")
  660. assert_equal "<fb:if-is-user uid=\"5678,1234\"></fb:if-is-user>", @h.fb_if_is_user([user1,user2]){}
  661. end
  662. def test_fb_else
  663. assert_equal "<fb:else></fb:else>", @h.fb_else{}
  664. end
  665. def test_fb_about_url
  666. ENV["FACEBOOK_API_KEY"]="1234"
  667. assert_equal "http://www.facebook.com/apps/application.php?api_key=1234", @h.fb_about_url
  668. end
  669. def test_fb_ref_with_url
  670. assert_equal "<fb:ref url=\"A URL\" />", @h.fb_ref(:url => "A URL")
  671. end
  672. def test_fb_ref_with_handle
  673. assert_equal "<fb:ref handle=\"A Handle\" />", @h.fb_ref(:handle => "A Handle")
  674. end
  675. def test_fb_ref_with_invalid_attribute
  676. assert_raises(ArgumentError) {@h.fb_ref(:handlee => "A HANLDE")}
  677. end
  678. def test_fb_ref_with_handle_and_url
  679. assert_raises(ArgumentError) {@h.fb_ref(:url => "URL", :handle => "HANDLE")}
  680. end
  681. def test_facebook_messages_notice
  682. @h.flash[:notice]="A message"
  683. assert_equal "<fb:success message=\"A message\" />",@h.facebook_messages
  684. end
  685. def test_facebook_messages_error
  686. @h.flash[:error]="An error"
  687. assert_equal "<fb:error message=\"An error\" />",@h.facebook_messages
  688. end
  689. def test_fb_wall_post
  690. assert_equal "<fb:wallpost uid=\"1234\">A wall post</fb:wallpost>",@h.fb_wall_post("1234","A wall post")
  691. end
  692. def test_fb_pronoun
  693. assert_equal "<fb:pronoun uid=\"1234\"></fb:pronoun>", @h.fb_pronoun(1234)
  694. end
  695. def test_fb_pronoun_with_transformed_key
  696. assert_equal "<fb:pronoun uid=\"1234\" usethey=\"true\"></fb:pronoun>", @h.fb_pronoun(1234, :use_they => true)
  697. end
  698. def test_fb_pronoun_with_user_responding_to_facebook_id
  699. user = flexmock("user", :facebook_id => "5678")
  700. assert_equal "<fb:pronoun uid=\"5678\"></fb:pronoun>", @h.fb_pronoun(user)
  701. end
  702. def test_fb_pronoun_with_invalid_key
  703. assert_raises(ArgumentError) {@h.fb_pronoun(1234, :posessive => true)}
  704. end
  705. def test_fb_wall
  706. @h.expects(:capture).returns("wall content")
  707. @h.fb_wall do
  708. end
  709. assert_equal "<fb:wall>wall content</fb:wall>",@h.output_buffer
  710. end
  711. def test_fb_multi_friend_request
  712. @h.expects(:capture).returns("body")
  713. @h.expects(:protect_against_forgery?).returns(false)
  714. @h.expects(:fb_multi_friend_selector).returns("friend selector")
  715. assert_equal "<fb:request-form action=\"action\" content=\"body\" invite=\"true\" method=\"post\" type=\"invite\">friend selector</fb:request-form>",
  716. (@h.fb_multi_friend_request("invite","ignored","action") {})
  717. end
  718. def test_fb_multi_friend_request_with_protection_against_forgery
  719. @h.expects(:capture).returns("body")
  720. @h.expects(:protect_against_forgery?).returns(true)
  721. @h.expects(:request_forgery_protection_token).returns('forgery_token')
  722. @h.expects(:form_authenticity_token).returns('form_token')
  723. @h.expects(:fb_multi_friend_selector).returns("friend selector")
  724. assert_equal "<fb:request-form action=\"action\" content=\"body\" invite=\"true\" method=\"post\" type=\"invite\">friend selector<input name=\"forgery_token\" type=\"hidden\" value=\"form_token\" /></fb:request-form>",
  725. (@h.fb_multi_friend_request("invite","ignored","action") {})
  726. end
  727. def test_fbjs_library
  728. @h.expects(:form_authenticity_token).returns('form_token')
  729. assert_equal "<script>var _token = 'form_token';var _hostname = 'http://facebook.host.com'</script><script src=\"http://facebook.host.com/javascripts/facebooker.js\" type=\"text/javascript\"></script>", @h.fbjs_library
  730. end
  731. def test_fb_dialog
  732. @h.expects(:capture).returns("dialog content")
  733. @h.fb_dialog( "my_dialog", true ) {}
  734. assert_equal '<fb:dialog cancel_button="1" id="my_dialog">dialog content</fb:dialog>', @h.output_buffer
  735. end
  736. def test_fb_dialog_title
  737. assert_equal '<fb:dialog-title>My Little Dialog</fb:dialog-title>', @h.fb_dialog_title("My Little Dialog")
  738. end
  739. def test_fb_dialog_content
  740. @h.expects(:capture).returns("dialog content content")
  741. @h.fb_dialog_content do
  742. end
  743. assert_equal '<fb:dialog-content>dialog content content</fb:dialog-content>', @h.output_buffer
  744. end
  745. def test_fb_dialog_button
  746. assert_equal '<fb:dialog-button clickrewriteform="my_form" clickrewriteid="my_dialog" clickrewriteurl="http://www.some_url_here.com/dialog_return.php" type="submit" value="Yes" />',
  747. @h.fb_dialog_button("submit", "Yes", {:clickrewriteurl => "http://www.some_url_here.com/dialog_return.php",
  748. :clickrewriteid => "my_dialog", :clickrewriteform => "my_form" } )
  749. end
  750. def test_fb_request_form
  751. @h.expects(:capture).returns("body")
  752. @h.expects(:protect_against_forgery?).returns(false)
  753. assert_equal "<fb:request-form action=\"action\" content=\"Test Param\" invite=\"true\" method=\"post\" type=\"invite\">body</fb:request-form>",
  754. (@h.fb_request_form("invite","test_param","action") {})
  755. end
  756. def test_fb_request_form_with_protect_against_forgery
  757. @h.expects(:capture).returns("body")
  758. @h.expects(:protect_against_forgery?).returns(true)
  759. @h.expects(:request_forgery_protection_token).returns('forgery_token')
  760. @h.expects(:form_authenticity_token).returns('form_token')
  761. assert_equal "<fb:request-form action=\"action\" content=\"Test Param\" invite=\"true\" method=\"post\" type=\"invite\">body<input name=\"forgery_token\" type=\"hidden\" value=\"form_token\" /></fb:request-form>",
  762. (@h.fb_request_form("invite","test_param","action") {})
  763. end
  764. def test_fb_error_with_only_message
  765. assert_equal "<fb:error message=\"Errors have occurred!!\" />", @h.fb_error("Errors have occurred!!")
  766. end
  767. def test_fb_error_with_message_and_text
  768. assert_equal "<fb:error><fb:message>Errors have occurred!!</fb:message>Label can't be blank!!</fb:error>", @h.fb_error("Errors have occurred!!", "Label can't be blank!!")
  769. end
  770. def test_fb_explanation_with_only_message
  771. assert_equal "<fb:explanation message=\"This is an explanation\" />", @h.fb_explanation("This is an explanation")
  772. end
  773. def test_fb_explanation_with_message_and_text
  774. assert_equal "<fb:explanation><fb:message>This is an explanation</fb:message>You have a match</fb:explanation>", @h.fb_explanation("This is an explanation", "You have a match")
  775. end
  776. def test_fb_success_with_only_message
  777. assert_equal "<fb:success message=\"Woot!!\" />", @h.fb_success("Woot!!")
  778. end
  779. def test_fb_success_with_message_and_text
  780. assert_equal "<fb:success><fb:message>Woot!!</fb:message>You Rock!!</fb:success>", @h.fb_success("Woot!!", "You Rock!!")
  781. end
  782. def test_facebook_form_for
  783. @h.expects(:protect_against_forgery?).returns(false)
  784. form_body=@h.facebook_form_for(:model,:url=>"action") do
  785. end
  786. assert_equal "<fb:editor action=\"action\"></fb:editor>",form_body
  787. end
  788. def test_facebook_form_for_with_authenticity_token
  789. @h.expects(:protect_against_forgery?).returns(true)
  790. @h.expects(:request_forgery_protection_token).returns('forgery_token')
  791. @h.expects(:form_authenticity_token).returns('form_token')
  792. assert_equal "<fb:editor action=\"action\"><input name=\"forgery_token\" type=\"hidden\" value=\"form_token\" /></fb:editor>",
  793. (@h.facebook_form_for(:model, :url => "action") {})
  794. end
  795. def test_fb_friend_selector
  796. assert_equal("<fb:friend-selector />",@h.fb_friend_selector)
  797. end
  798. def test_fb_request_form_submit
  799. assert_equal("<fb:request-form-submit />",@h.fb_request_form_submit)
  800. end
  801. def test_fb_request_form_submit_with_uid
  802. assert_equal("<fb:request-form-submit uid=\"123456789\" />",@h.fb_request_form_submit({:uid => "123456789"}))
  803. end
  804. def test_fb_request_form_submit_with_label
  805. assert_equal("<fb:request-form-submit label=\"Send Invite to Joel\" />",@h.fb_request_form_submit({:label => "Send Invite to Joel"}))
  806. end
  807. def test_fb_request_form_submit_with_uid_and_label
  808. assert_equal("<fb:request-form-submit label=\"Send Invite to Joel\" uid=\"123456789\" />",@h.fb_request_form_submit({:uid =>"123456789", :label => "Send Invite to Joel"}))
  809. end
  810. def test_fb_action
  811. assert_equal "<fb:action href=\"/growingpets/rub\">Rub my pet</fb:action>", @h.fb_action("Rub my pet", "/growingpets/rub")
  812. end
  813. def test_fb_help
  814. assert_equal "<fb:help href=\"http://www.facebook.com/apps/application.php?id=6236036681\">Help</fb:help>", @h.fb_help("Help", "http://www.facebook.com/apps/application.php?id=6236036681")
  815. end
  816. def test_fb_create_button
  817. assert_equal "<fb:create-button href=\"/growingpets/invite\">Invite Friends</fb:create-button>", @h.fb_create_button('Invite Friends', '/growingpets/invite')
  818. end
  819. def test_fb_comments_a_1
  820. assert_equal "<fb:comments candelete=\"false\" canpost=\"true\" numposts=\"7\" showform=\"true\" xid=\"a:1\"></fb:comments>", @h.fb_comments("a:1",true,false,7,:showform=>true)
  821. end
  822. def test_fb_comments_xxx
  823. assert_equal "<fb:comments candelete=\"false\" canpost=\"true\" numposts=\"4\" optional=\"false\" xid=\"xxx\"></fb:comments>", @h.fb_comments("xxx",true,false,4,:optional=>false)
  824. end
  825. def test_fb_comments_with_title
  826. assert_equal "<fb:comments candelete=\"false\" canpost=\"true\" numposts=\"4\" optional=\"false\" xid=\"xxx\"><fb:title>TITLE</fb:title></fb:comments>", @h.fb_comments("xxx",true,false,4,:optional=>false, :title => "TITLE")
  827. end
  828. def test_fb_board
  829. assert_equal "<fb:board optional=\"false\" xid=\"xxx\"></fb:board>", @h.fb_board("xxx",:optional => false)
  830. end
  831. def test_fb_board_with_title
  832. assert_equal "<fb:board optional=\"false\" xid=\"xxx\"><fb:title>TITLE</fb:title></fb:board>", @h.fb_board("xxx",:optional=>false, :title => "TITLE")
  833. end
  834. def test_fb_dashboard
  835. @h.expects(:capture).returns("dashboard content")
  836. @h.fb_dashboard do
  837. end
  838. assert_equal "<fb:dashboard>dashboard content</fb:dashboard>", @h.output_buffer
  839. end
  840. def test_fb_dashboard_non_block
  841. assert_equal "<fb:dashboard></fb:dashboard>", @h.fb_dashboard
  842. end
  843. def test_fb_wide
  844. @h.expects(:capture).returns("wide profile content")
  845. @h.fb_wide do
  846. end
  847. assert_equal "<fb:wide>wide profile content</fb:wide>", @h.output_buffer
  848. end
  849. def test_fb_narrow
  850. @h.expects(:capture).returns("narrow profile content")
  851. @h.fb_narrow do
  852. end
  853. assert_equal "<fb:narrow>narrow profile content</fb:narrow>", @h.output_buffer
  854. end
  855. def test_fb_login_button
  856. assert_equal "<fb:login-button onlogin=\"somejs\"></fb:login-button>",@h.fb_login_button("somejs")
  857. assert_equal "<fb:login-button onlogin=\"somejs\">Custom</fb:login-button>",@h.fb_login_button("somejs", :text => 'Custom')
  858. end
  859. def test_init_fb_connect_no_features
  860. assert ! @h.init_fb_connect.match(/XFBML/)
  861. end
  862. def test_init_fb_connect_with_features
  863. assert @h.init_fb_connect("XFBML").match(/XFBML/)
  864. end
  865. def test_init_fb_connect_receiver_path
  866. assert @h.init_fb_connect.match(/xd_receiver.html/)
  867. end
  868. def test_init_fb_connect_receiver_path_ssl
  869. @h.instance_eval do
  870. def request
  871. ssl_request = ActionController::TestRequest.new
  872. ssl_request.stubs(:ssl?).returns(true)
  873. ssl_request
  874. end
  875. end
  876. assert @h.init_fb_connect.match(/xd_receiver_ssl.html/)
  877. end
  878. def test_init_fb_connect_with_features_and_body
  879. @h.expects(:capture).returns("Body Content")
  880. __in_erb_template = true
  881. @h.init_fb_connect("XFBML") do
  882. end
  883. assert @h.output_buffer =~ /Body Content/
  884. end
  885. def test_init_fb_connect_no_options
  886. assert ! @h.init_fb_connect.match(/Element.observe\(window,'load',/)
  887. end
  888. def test_init_fb_connect_with_options_js_jquery
  889. assert ! @h.init_fb_connect(:js => :jquery).match(/\$\(document\).ready\(/)
  890. end
  891. def test_init_fb_connect_with_options_js_mootools
  892. assert @h.init_fb_connect("XFBML", :js => :mootools).match(/window.addEvent\('domready',/)
  893. end
  894. def test_init_fb_connect_with_features_and_options_js_jquery
  895. assert @h.init_fb_connect("XFBML", :js => :jquery).match(/XFBML.*/)
  896. assert @h.init_fb_connect("XFBML", :js => :jquery).match(/\jQuery\(document\).ready\(/)
  897. end
  898. def test_init_fb_connect_without_options_app_settings
  899. assert @h.init_fb_connect().match(/, \{\}\)/)
  900. end
  901. def test_init_fb_connect_with_options_app_settings
  902. assert @h.init_fb_connect(:app_settings => "{foo: bar}").match(/, \{foo: bar\}\)/)
  903. end
  904. def test_fb_login_and_redirect
  905. assert_equal @h.fb_login_and_redirect("/path"),"<fb:login-button onlogin=\"window.location.href = &quot;/path&quot;;\"></fb:login-button>"
  906. assert_equal @h.fb_login_and_redirect("/path", :text => 'foo'),"<fb:login-button onlogin=\"window.location.href = &quot;/path&quot;;\">foo</fb:login-button>"
  907. end
  908. def test_fb_logout_link
  909. assert_equal @h.fb_logout_link("Logout","My URL"),"<a href=\"#\" onclick=\"FB.Connect.logoutAndRedirect(&quot;My URL&quot;);\nwindow.location.href = &quot;My URL&quot;;; return false;\">Logout</a>"
  910. end
  911. def test_fb_bookmark_link
  912. assert_equal @h.fb_bookmark_link("Bookmark","My URL"),"<a href=\"#\" onclick=\"FB.Connect.showBookmarkDialog(&quot;My URL&quot;);; return false;\">Bookmark</a>"
  913. end
  914. def test_fb_user_action_with_literal_callback
  915. action = Facebooker::Rails::Publisher::UserAction.new
  916. assert_equal "FB.Connect.showFeedDialog(null, null, null, null, null, FB.RequireConnect.promptConnect, function() {alert('hi')}, \"prompt\", #{{"value" => "message"}.to_json});",
  917. @h.fb_user_action(action,"message","prompt","function() {alert('hi')}")
  918. end
  919. def test_fb_user_action_with_nil_callback
  920. action = Facebooker::Rails::Publisher::UserAction.new
  921. assert_equal "FB.Connect.showFeedDialog(null, null, null, null, null, FB.RequireConnect.promptConnect, null, \"prompt\", #{{"value" => "message"}.to_json});",
  922. @h.fb_user_action(action,"message","prompt")
  923. end
  924. def test_fb_connect_stream_publish
  925. stream_post = Facebooker::StreamPost.new
  926. attachment = Facebooker::Attachment.new
  927. attachment.name="name"
  928. stream_post.message = "message"
  929. stream_post.target="12451752"
  930. stream_post.attachment = attachment
  931. assert @h.fb_connect_stream_publish(stream_post).match(/FB.Connect\.streamPublish\(\"message\", \{\"name\":\s?\"name\"\}, \[\], \"12451752\", null, null, false, null\);/)
  932. end
  933. def test_fb_stream_publish
  934. stream_post = Facebooker::StreamPost.new
  935. attachment = Facebooker::Attachment.new
  936. attachment.name="name"
  937. stream_post.message = "message"
  938. stream_post.target="12451752"
  939. stream_post.attachment = attachment
  940. assert @h.fb_stream_publish(stream_post).match(/Facebook\.streamPublish\(\"message\", \{\"name\":\s?\"name\"\}, \[\], \"12451752\", null, null, false, null\);/)
  941. end
  942. def test_fb_connect_javascript_tag
  943. silence_warnings do
  944. assert_equal "<script src=\"http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php\" type=\"text/javascript\"></script>",
  945. @h.fb_connect_javascript_tag
  946. end
  947. end
  948. def test_fb_connect_javascript_tag_with_language_option
  949. silence_warnings do
  950. assert_equal "<script src=\"http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php/en_US\" type=\"text/javascript\"></script>",
  951. @h.fb_connect_javascript_tag(:lang => "en_US")
  952. end
  953. end
  954. def test_fb_connect_javascript_tag_ssl
  955. @h.instance_eval do
  956. def request
  957. ssl_request = ActionController::TestRequest.new
  958. ssl_request.stubs(:ssl?).returns(true)
  959. ssl_request
  960. end
  961. end
  962. silence_warnings do
  963. assert_equal "<script src=\"https://ssl.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php\" type=\"text/javascript\"></script>",
  964. @h.fb_connect_javascript_tag
  965. end
  966. end
  967. def test_fb_connect_javascript_tag_ssl_with_language_option
  968. @h.instance_eval do
  969. def request
  970. ssl_request = ActionController::TestRequest.new
  971. ssl_request.stubs(:ssl?).returns(true)
  972. ssl_request
  973. end
  974. end
  975. silence_warnings do
  976. assert_equal "<script src=\"https://ssl.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php/en_US\" type=\"text/javascript\"></script>",
  977. @h.fb_connect_javascript_tag(:lang => "en_US")
  978. end
  979. end
  980. def test_fb_container
  981. @h.expects(:capture).returns("Inner Stuff")
  982. @h.fb_container(:condition=>"somejs") do
  983. end
  984. assert_equal "<fb:container condition=\"somejs\">Inner Stuff</fb:container>",@h.output_buffer
  985. end
  986. def test_fb_eventlink
  987. assert_equal '<fb:eventlink eid="21150032416"></fb:eventlink>',@h.fb_eventlink("21150032416")
  988. end
  989. def test_fb_grouplink
  990. assert_equal '<fb:grouplink gid="2541896821"></fb:grouplink>',@h.fb_grouplink("2541896821")
  991. end
  992. def test_fb_serverfbml
  993. @h.expects(:capture).returns("Inner Stuff")
  994. @h.fb_serverfbml(:condition=>"somejs") do
  995. end
  996. assert_equal "<fb:serverfbml condition=\"somejs\">Inner Stuff</fb:serverfbml>",@h.output_buffer
  997. end
  998. def test_fb_share_button
  999. assert_equal "<fb:share-button class=\"url\" href=\"http://www.elevatedrails.com\"></fb:share-button>",@h.fb_share_button("http://www.elevatedrails.com")
  1000. end
  1001. def test_fb_unconnected_friends_count_without_condition
  1002. assert_equal "<fb:unconnected-friends-count></fb:unconnected-friends-count>",@h.fb_unconnected_friends_count
  1003. end
  1004. def test_fb_user_status
  1005. user=flexmock("user", :facebook_id => "5678")
  1006. assert_equal '<fb:user-status linked="false" uid="5678"></fb:user-status>',@h.fb_user_status(user,false)
  1007. end
  1008. def test_fb_time
  1009. time = Time.now
  1010. assert_equal %Q{<fb:time preposition="true" t="#{time.to_i}" tz="America/New York" />}, @h.fb_time(time, :tz => 'America/New York', :preposition => true)
  1011. end
  1012. def test_fb_time_defaults
  1013. time = Time.now
  1014. assert_equal %Q{<fb:time t="#{time.to_i}" />}, @h.fb_time(time)
  1015. end
  1016. end
  1017. class TestModel
  1018. attr_accessor :name,:facebook_id
  1019. end
  1020. class RailsFacebookFormbuilderTest < Test::Unit::TestCase
  1021. class TestTemplate
  1022. include ActionView::Helpers::TextHelper
  1023. include ActionView::Helpers::CaptureHelper
  1024. include ActionView::Helpers::TagHelper
  1025. include Facebooker::Rails::Helpers
  1026. attr_accessor :output_buffer
  1027. def initialize
  1028. @output_buffer=""
  1029. end
  1030. end
  1031. def setup
  1032. @_erbout = ""
  1033. @test_model = TestModel.new
  1034. @test_model.name="Mike"
  1035. @template = TestTemplate.new
  1036. @proc = Proc.new {}
  1037. @form_builder = Facebooker::Rails::FacebookFormBuilder.new(:test_model,@test_model,@template,{},@proc)
  1038. def @form_builder._erbout
  1039. ""
  1040. end
  1041. end
  1042. def test_text_field
  1043. assert_equal "<fb:editor-text id=\"test_model_name\" label=\"Name\" name=\"test_model[name]\" value=\"Mike\"></fb:editor-text>",
  1044. @form_builder.text_field(:name)
  1045. end
  1046. def test_text_area
  1047. assert_equal "<fb:editor-textarea id=\"test_model_name\" label=\"Name\" name=\"test_model[name]\">Mike</fb:editor-textarea>",
  1048. @form_builder.text_area(:name)
  1049. end
  1050. def test_default_name_and_id
  1051. assert_equal "<fb:editor-text id=\"different_id\" label=\"Name\" name=\"different_name\" value=\"Mike\"></fb:editor-text>",
  1052. @form_builder.text_field(:name, {:name => 'different_name', :id => 'different_id'})
  1053. end
  1054. def test_collection_typeahead
  1055. flexmock(@form_builder) do |fb|
  1056. fb.should_receive(:collection_typeahead_internal).with(:name,["ABC"],:size,:to_s,{})
  1057. end
  1058. @form_builder.collection_typeahead(:name,["ABC"],:size,:to_s)
  1059. end
  1060. def test_collection_typeahead_internal
  1061. assert_equal "<fb:typeahea…

Large files files are truncated, but you can click here to view the full file