factory_girl rspec测试失败,使用before_filter

时间:2011-12-19 16:14:30

标签: ruby-on-rails-3 rspec factory-bot

我这里有一个新手问题。我一直在跟踪rails教程,我在测试中遇到了麻烦。当我实现以下过滤器时......

class UsersController < ApplicationController
before_filter :authenticate, :only => [:edit, :update]

...与'GET edit'和'PUT update'相关的所有user_controller_spec.rb测试在它们通过之前开始失败。这里应该返回true,但返回false:

describe "GET 'edit" do

 before(:each) do
   @user = Factory(:user)
   test_sign_in(@user)
 end

 it "should be successful" do
   get :edit, :id => @user
   response.should be_success
 end
end

这是我在spec_helper.rb中的test_sign_in代码

def test_sign_in(user)
 controller.sign_in(user)
end

sign_in方法位于SessionsHelper中,它在ApplicationController中包含:

def sign_in(user)
 cookies.permanent.signed[:remember_token] = [user.id, user.salt]
 current_user = user
end

我不知道如何进一步调查。我的猜测是,由于Rspec无法“GET edit”,我必须查看该请求的日志,但测试只告诉我它返回false。我在哪里可以看下一个?

更新:我在log / test.log中发现的是每个'Processing by UsersController #index as HTML'行后面都有一个重定向,如下所示:

  Processing by UsersController#index as HTML
  [1m [35mUser Load (0.2ms) [0m  SELECT "users".* FROM "users" WHERE "users"."id" IS NULL LIMIT 1
  Redirected to http://test.host/signin

这是否意味着每个测试索引操作后面都会重定向以进行登录?如果这是真的,它似乎与测试一致,包括test_sign_in方法(上面)失败以及其他测试如下:

describe "GET 'index' for non-signed-in users" do     
  it "should deny access" do
    get :index
    response.should redirect_to(signin_path)
  end
end

我将尝试再次围绕test_sign_in方法。

1 个答案:

答案 0 :(得分:2)

您需要在self帮助程序中调用sign_in

def sign_in(user)
  cookies.permanent.signed[:remember_token] = [user.id, user.salt]
  self.current_user = user
end