require 'ostruct' require 'test/unit' require File.join(File.dirname(__FILE__),"..","lib","refcode.rb") class RefcodeEncodableTest < Test::Unit::TestCase SECRET = "a short tidy secret, but not too short!" class BareEncodableObject < OpenStruct include Refcode::Encodable end class EncodableObjectSymbol < BareEncodableObject has_refcode :secret => SECRET, :salt => :record_id end class EncodableObjectString < BareEncodableObject has_refcode :secret => SECRET, :salt => "123 abc xyz" end class EncodableObjectSaltyLambda < BareEncodableObject has_refcode :secret => SECRET, :salt => lambda { |me| "#{me.record_id}-42" } end def test_should_raise_argument_error_if_generate_refcode_called_without_val assert_raise ArgumentError do encodable_object.generate_refcode end end def test_should_raise_error_if_refcode_methods_called_before_has_refcode [:generate_refcode, :parse_refcode].each do |m| assert_raise Refcode::RefcodeInitException do obj = BareEncodableObject.new :some => 'value' obj.send m, "bogus value" end end end def test_should_raise_argument_error_if_has_refcode_called_without_correct_options assert_raise ArgumentError do obj = BareEncodableObject.new :some => 'value' obj.class.has_refcode :whatever => 'wrong' end end def test_should_raise_an_error_if_salt_is_empty encodable_object.record_id = nil assert_raise RuntimeError do referral_code_content = { :channel => 'email', :action => 'forward', :user_id => 14325 } code = encodable_object.generate_refcode referral_code_content assert_equal referral_code_content, encodable_object.parse_refcode(code) end end def test_should_work_with_different_salt_options [EncodableObjectSaltyLambda, EncodableObjectString].each do |klass| referral_code_content = { :channel => 'email', :action => 'forward', :user_id => 14325 } obj = klass.new referral_code_content code = obj.generate_refcode referral_code_content assert_equal referral_code_content, obj.parse_refcode(code) end end def test_encodable_against_hash referral_code_content = { :channel => 'email', :action => 'forward', :user_id => 14325 } code = encodable_object.generate_refcode referral_code_content assert_equal referral_code_content, encodable_object.parse_refcode(code) end private def encodable_object @encodable_object ||= EncodableObjectSymbol.new :name => 'Unimportant Value', :record_id => 381598 end end