[rspec-users] Testing User Agent

Nick Hoffman nick at deadorange.com
Wed Feb 25 16:39:52 EST 2009


On 25/02/2009, at 4:51 AM, Suprie Leonhart wrote:
> On Wed, Feb 25, 2009 at 4:19 PM, David Chelimsky  
> <dchelimsky at gmail.com> wrote:
> On Wed, Feb 25, 2009 at 1:57 AM, Suprie Leonhart
> <suprie.leonheart at gmail.com> wrote:
> > hi
> >
> > i'm testing some lib i've made for detecting mobile user agent, I  
> confused
> > how to test the lib i've made.
> > the test code is
> >
> > [code]
> >
> >   describe "Check if mobile browser" do
> >     it "should know if it's from blackberry" do
> >       blackberry_ua = "BlackBerry8330/4.3.0 Profile/MIDP-2.0
> > Configuration/CLDC-1.1 VendorID/105"
> >       request.env["HTTP_USER_AGENT"] = blackberry_ua
> >       is_mobile?.should == true
> >     end
> >   end
> >
> > [/code]
> >
> > the error is, request variable always nil
> >
> > the question : how i mock the request.env ?
>
> Since you're trying to test existing code, can you please post that  
> code?
>
> [code]
> module Mobile
>   def load_mobile_agent_file
>     ma = File.read(RAILS_ROOT+"/config/mobile.yml")
>     yaml = YAML.load(ma)
>     return yaml
>   end
>
>   def mobile_user_agent?
>     if request.env["HTTP_USER_AGENT"]
>       user_agent  = request.env["HTTP_USER_AGENT"]
>       mua         = load_mobile_agent_file
>       mua["mobile_agent"].each do |key, value|
>         unless(user_agent.match(Regexp.new(Regexp.escape(key))).nil?)
>           return true
>         end
>       end
>       return false
>     end
>   end
> end
> [/code]
>
> -- 
> --
> Best Regards
> Suprie
> http://suprie.in.ruangkopi.com

Hi Suprie. AFAIK, RSpec populates the "request" object in your specs  
after a controller action is called. Since your "should know if it's  
from blackberry" example doesn't call a controller action, the  
"request" object is nil.
-Nick


More information about the rspec-users mailing list