简体   繁体   English

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

[英]Rspec method returning a value which should be a redirect

I have: 我有:

def redirect_if_no_user
  if current_user.nil?
    redirect_to root_path
  end
end

in ApplicatonController . ApplicatonController I would like to write a corresponding test: 我想写一个相应的测试:

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

but I'm getting: Expected response to be a <redirect>, but was <200> 但我得到: Expected response to be a <redirect>, but was <200>

Any help? 有什么帮助吗?

When you write current_user = nil it will set a local variable. 当您编写current_user = nil ,它将设置一个局部变量。 You need to nil out the controller's current_user which comes from its @current_user instance var. 您需要取消来自其@current_user实例var的控制器的current_user Or stub out the controller's current_user method to return nil. 或存根控制器的current_user方法以返回nil。

Your anonymous controller does not call the filter, so add: 您的匿名控制器不会调用过滤器,因此请添加:

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

also test expect(current_user).to be_nil if defined? current_user expect(current_user).to be_nil if defined? current_user还可以测试expect(current_user).to be_nil if defined? current_user expect(current_user).to be_nil if defined? current_user just to ensure correct input expect(current_user).to be_nil if defined? current_user只是为了确保输入正确

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM