Rspec方法返回一个应该是重定向的值

时间:2016-02-01 13:51:44

标签: ruby-on-rails ruby rspec

我有:

def redirect_if_no_user
  if current_user.nil?
    redirect_to root_path
  end
end
ApplicatonController中的

。我想写一个相应的测试:

Rspec.describe ApplicationController do

controller do
  def index
    render nothing: true
  end
end

describe '#redirect_if_no_user' do
  it 'redirects to root path' do
    get :index
    current_user = nil
    expect(response).to redirect_to(root_path)
  end
end

end

但我得到了:Expected response to be a <redirect>, but was <200>

任何帮助?

2 个答案:

答案 0 :(得分:1)

当你写current_user = nil时,它会设置一个局部变量。你需要找出来自current_user实例var的控制器@current_user。或者将控制器的current_user方法固定为nil。

答案 1 :(得分:0)

您的匿名控制器未调用过滤器,因此请添加:

controller do
  before_filter :redirect_if_no_user # so it is called
  def index
    render nothing: true
  end
end

还要测试expect(current_user).to be_nil if defined? current_user以确保输入正确