简体   繁体   English

如何为控制器编写适当的rspec测试

[英]How to write proper rspec test for controller

I have controller called Application controller with next method for which I want to write test for: 我有一个名为“应用程序控制器”的控制器,下面是我要为其编写测试的下一个方法:

  def require_admin
    p current_user.role
    return if current_user && current_user.role == 'admin'
    flash[:error] = "You are not an admin"
    redirect_to root_path
  end

How to write proper test for it, and what kind of test should it be? 如何为此编写适当的测试,应该是哪种测试?

You shouldn't test implementation. 您不应该测试实现。 Try testing 'how should this controller action behave for a non-admin user', it might look like this: 尝试测试“此控制器操作对非管理员用户应如何表现”,它可能看起来像这样:

context 'user who is not an admin' do
  before do
    user.role = 'not_admin'
    get :some_action
  end

  it 'is redirected to root_path' do        
    expect(response).to redirect_to('/')
  end
  ...
end

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

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