diff --git a/lib/ferrum/cookies/cookie.rb b/lib/ferrum/cookies/cookie.rb index 77d73c7d..d6345cd1 100644 --- a/lib/ferrum/cookies/cookie.rb +++ b/lib/ferrum/cookies/cookie.rb @@ -121,6 +121,29 @@ def expires def ==(other) other.class == self.class && other.attributes == attributes end + + # + # Converts the cookie back into a raw cookie String. + # + # @return [String] + # The raw cookie string. + # + def to_s + string = String.new("#{@attributes['name']}=#{@attributes['value']}") + + @attributes.each do |key,value| + case key + when 'name', 'value' # no-op + when 'domain' then string << "; Domain=#{value}" + when 'path' then string << "; Path=#{value}" + when 'expires' then string << "; Expires=#{Time.at(value).httpdate}" + when 'httpOnly' then string << "; httpOnly" if value + when 'secure' then string << "; Secure" if value + end + end + + return string + end end end end diff --git a/spec/cookies/cookie_spec.rb b/spec/cookies/cookie_spec.rb index 2a096f41..b177cdb0 100644 --- a/spec/cookies/cookie_spec.rb +++ b/spec/cookies/cookie_spec.rb @@ -112,4 +112,95 @@ end end end + + describe "#to_s" do + let(:name) { 'foo' } + let(:value) { 'bar' } + + context "when only 'name' and 'value' attributes are set" do + let(:attributes) do + { + 'name' => name, + 'value' => value + } + end + + it "must only return 'name=value'" do + expect(subject.to_s).to eq("#{name}=#{value}") + end + end + + context "when the 'domain' attribute is set" do + let(:domain) { 'example.com' } + let(:attributes) do + { + 'name' => name, + 'value' => value, + 'domain' => domain + } + end + + it "must include the 'Domain=' attribute in the String" do + expect(subject.to_s).to eq("#{name}=#{value}; Domain=#{domain}") + end + end + + context "when the 'path' attribute is set" do + let(:path) { '/' } + let(:attributes) do + { + 'name' => name, + 'value' => value, + 'path' => path + } + end + + it "must include the 'Path=' attribute in the String" do + expect(subject.to_s).to eq("#{name}=#{value}; Path=#{path}") + end + end + + context "when the 'expires' attribute is set" do + let(:expires) { 1691287370 } + let(:attributes) do + { + 'name' => name, + 'value' => value, + 'expires' => expires + } + end + + it "must include the 'Expires=' attribute and HTTP formatted time in the String" do + expect(subject.to_s).to eq("#{name}=#{value}; Expires=#{Time.at(expires).httpdate}") + end + end + + context "when the 'httpOnly' attribute is set" do + let(:attributes) do + { + 'name' => name, + 'value' => value, + 'httpOnly' => true + } + end + + it "must include the 'httpOnly' flag in the String" do + expect(subject.to_s).to eq("#{name}=#{value}; httpOnly") + end + end + + context "when the 'secure' attribute is set" do + let(:attributes) do + { + 'name' => name, + 'value' => value, + 'secure' => true + } + end + + it "must include the 'Secure' flag in the String" do + expect(subject.to_s).to eq("#{name}=#{value}; Secure") + end + end + end end