Agile with rails 一书中详细的描述了如何进行测试,
但是在开发中,我们或许会遇到下面的情况:

用户必须登陆系统才能进行其他工作;
用户信息保存在 session 里;
登陆工作是在 单独的 controller里(如 LoginController).

这样的情况下, 当我们想对 SearchController 进行功能测试的时候,
会遇到没有权限访问action的情况.
但是我们又不能在 SearchContrller_test 里调用 LoginController_test,
那么如何处理呢?

以下是我的解决办法:

def setup
    @controller = ReportController.new
    @request    = ActionController::TestRequest.new
    @response   = ActionController::TestResponse.new
    
    test_user
  end

def test_user
    
    # 这个 @tom  是 fixtures 中的数据
    @user = User.find(:first, :conditions=>['id=?', @tom.id])
    assert_not_nil @user
    
  end

def test_index
    
    #权限校验的规则就是如果 session[:app_user] not null, 就说明登陆了
    get :index,{}, :app_user=>@user
    
    assert_response :success
    
  end



方法很简单,就是 在 get(post) 方法里,设置 session的数值.


如果还有更好的办法希望能共享出来, thanks!
评论
yananay
搜索本博客
我的相册
D35bafa8-5bf0-475f-aa06-16f3080557a1-thumb
tdd
共 3 张
存档
最新评论