Here's a quick rspec stubbing tip for those of you using RSpec and Spec::Rails with a need to stub out the controller behavior for ssl_required. I wrote this tip with mocha in mind, but you can easily apply this to whatever mocking/stubbing framework you may be using.
First, let's take a look at the source for the SslRequirement module, paying attention to the the before_filter bit:
module SslRequirement
def self.included(controller)
controller.extend(ClassMethods)
controller.before_filter(:ensure_proper_protocol)
end
...
private
def ensure_proper_protocol
return true if ssl_allowed?
if ssl_required? && !request.ssl?
redirect_to "https://" + request.host + request.request_uri
flash.keep
return false
elsif request.ssl? && !ssl_required?
redirect_to "http://" + request.host + request.request_uri
flash.keep
return false
end
end
end
You can see that it is the private method ensure_proper_protocol that is being declared as a filter for the controller. Since a controller that declares ssl_required will automatically inherit the methods listed in SslRequirement, you can stub the SSL-checking behavior in mocha-style for your controller's behavior-driven rspec test like so:
controller.stub!(:ensure_proper_protocol).and_return(:true)
Just declare the above stubbing in a setup block, and you are good to go!
3 comments:
I know this is an old post, but I just found it, and it worked like a charm for me. Thank you!
Hey, glad to know some of the stuff I write about is still useful. Cheers!
Worked for me too, four years later! Cheers!
Post a Comment