注册 | 登录 忘记密码? 51cto首页 | 博客 | 论坛 | 招聘
热点文章 GHOST系统封装 全图 教程
 帮助

Rails 2.0: HTTP Basic Authentication Test


2008-02-23 21:41:54
版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://blackanger.blog.51cto.com/140924/62929
老外Andy比较守旧,写测试不让用Rspec,所以我又回归到了Rails自带的unit test 。又感觉他有点变态,develop的时候加什么验证,搞的我很郁闷。如果我用Rspec,就很简单了,可以这么写:

在Application.rb里:
class ApplicationController < ActionController::Base

        before_filter :authenticate

        def authenticate
          authenticate_or_request_with_http_basic do |username, password|
            username == 'jared' && password == 'secret'
          end
        end
    end
Test里这么写:
describe WidgetsController do
  describe "with successful admin login" do
    before(:each) do
         controller.stub!(:authenticate).and_return(true)
    end
    ...
    end
end



但是我现在用Rails自带的unit test的话,只能自己去定义个方法:
def set_basic_authentication
  @request.env['HTTP_AUTHORIZATION'] = 'Basic ' + Base64::b64encode("#{Configuration::ADMIN[:username]}:#{Configuration::ADMIN[:password]}")
end

then:
你可以写到setup方法里:
def setup
@controller = AdminController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
set_basic_authentication
end

但是还需要测试没有输入密码失败的情况,所以就不能放到setup方法里了,需要用到的测试方法里调用这个set_basic_authentication方法就行了,比如:
def test_basic_authentication_success
    set_basic_authentication
    get :index
    assert_response :success
end

这样就了我一桩心事了。


本文出自 “{ :Alex Space => " Ruby Notes " }” 博客,请务必保留此出处http://blackanger.blog.51cto.com/140924/62929





    文章评论
 
2008-02-24 20:15:59
恩 不错的

 

发表评论

昵   称:
验证码:  点击图片可刷新验证码  博客过2级,无需填写验证码
内   容: