19
Jul
09

Mock Cookies in Rails Tests the Easy Way

I got really tired of mocking out cookies every single time I made a reference to cookies in my test. It looked like a bunch of spaghetti code that made me mock out every single cookie call that I could imagine. Don’t get me wrong, I think mocks are wonderful, but when you have to mock out every single call, I don’t think the pain is worth the gain. I found it much easier to mock cookies like this as like this, which gives a pretty good approximation of rails cookies. It won’t work for 100% of cookie testing cases, but for 99.9%, it works like a charm.

I use rspec to test, but you could easily port the Cookie class to any testing framework that you want.

def stub_cookies
  stub!(:cookies).and_return(MockCookie.new)
end

class MockCookie < Hash

  def [](name)
    super(name.to_s)
  end
 
  def []=(key, options)
    if options.is_a?(Hash)
      options.symbolize_keys!
    else
      options = { :value => options }
    end
    super(key.to_s, options[:value])
   end

  def delete(key,opts)
    super(key)
  end

end

Advertisement

0 Responses to “Mock Cookies in Rails Tests the Easy Way”



  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s


Stay Updated

or

Get new posts via email

Software Blogs - BlogCatalog Blog Directory

 

July 2009
M T W T F S S
« Jun    
 12345
6789101112
13141516171819
20212223242526
2728293031  

Follow

Get every new post delivered to your Inbox.