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”