【问题标题】:Testing a redirect outside of a controller在控制器外测试重定向
【发布时间】:2015-05-08 13:27:38
【问题描述】:

我有一个辅助模块,如果当前用户没有访问网页的权限,它会触发 redirect_to

我在运行测试时收到NoMethodError 错误,因为帮助程序实际上没有redirect_to 方法。我试过像这样删除redirect_to:

it "redirects the user to the user's langing page if the user doesn't have permission" do
  allow(helper).to receive(:current_or_guest_user) { test_user }
  expect(helper).to receive(:redirect_to)
  helper.require_permission :view_admins
end

但是我得到一个很长很长的错误,助手没有实现redirect_to

有没有办法把这个方法去掉?

【问题讨论】:

  • redirect_to 是一种动作控制器方法,因此只能在控制器中使用
  • 是的,但这是一个将包含在控制器中的模块,所以它工作得很好 - 我只是不确定如何测试它。

标签: ruby-on-rails rspec mocking


【解决方案1】:

您可以在您的规范中创建一个anonymous 控制器并将您的模块包含在其中。完成后,您可以像普通控制器操作/方法一样对其进行测试。所以,在你的规范中添加一些类似的东西:

controller(YourController) do
  include YourModule

  def index
    render text: 'body'
  end
end

我不知道您的方法是否为before_action,但似乎是因为您正在测试用户是否具有所需的view_admins 权限。

因此,当用户拥有所需的权限时,您的规范应该是这样的:

context 'when the user has the required permission' do
  before do
    # make sure the user has the required permission
  end

  it 'the user will see the rendered text' do
    get :index
    expect(response.body).to eq 'body'
  end
end

当用户没有所需的权限时,他们将被重定向到您定义的路径。所以,是这样的:

context 'when the user does NOT have the required permission' do
  before do
    # make sure the user does NOT have the required permission
  end

  it 'the user will be redirected to the specified path' do
    get :index
    expect(controller).to redirect_to your_specified_path
  end
end

更多关于anonymous控制器的信息可以在here找到。

【讨论】:

    猜你喜欢
    • 2013-05-02
    • 1970-01-01
    • 2014-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多