ruby-on-rails - Rails、Restful Authentication 和 RSpec - 如何测试需要身份验证的新模型

标签 ruby-on-rails testing rspec restful-authentication

我使用 Bort 创建了一个学习应用程序,这是一个包含 Restful Authentication 和 RSpec 的基础应用程序。我已经启动并运行它并添加了一个新对象,该对象要求用户在执行任何操作之前先登录(before_filter :login_required 在 Controller 中)。 [编辑:我还应该提到新类的用户 has_many 并且只有该用户应该能够看到它。]

我使用 Rspec 的生成器创建了新的模型/ Controller ,这些生成器创建了许多默认测试。如果没有 before_filter,它们都会通过,但如预期的那样,一旦 before_filter 到位,有几个会失败。

如何让生成的测试像有/没有登录用户一样运行?我是否需要整批匹配未登录-重定向测试?我认为这是某种模拟或夹具技术,但我是 RSpec 的新手并且有点随波逐流。良好的 RSpec 教程链接也将不胜感激。

最佳答案

我有一个非常相似的设置,下面是我目前用来测试这些东西的代码。在我输入的每个 describe 中:

it_should_behave_like "login-required object"
def attempt_access; do_post; end

如果您只需要登录,或者

it_should_behave_like "ownership-required object"
def login_as_object_owner; login_as @product.user; end
def attempt_access; do_put; end
def successful_ownership_access
  response.should redirect_to(product_url(@product))
end

如果您需要所有权。显然,辅助方法在每一轮都发生变化(很少),但这会为您完成大部分工作。这是在我的 spec_helper.rb 中

shared_examples_for "login-required object" do
  it "should not be able to access this without logging in" do
    attempt_access

    response.should_not be_success
    respond_to do |format|
      format.html { redirect_to(login_url) }
      format.xml { response.status_code.should == 401 }
    end
  end
end

shared_examples_for "ownership-required object" do
  it_should_behave_like "login-required object"

  it "should not be able to access this without owning it" do
    attempt_access

    response.should_not be_success
    respond_to do |format|
      format.html { response.should be_redirect }
      format.xml { response.status_code.should == 401 }
    end
  end

  it "should be able to access this if you own it" do
    login_as_object_owner
    attempt_access

    if respond_to?(:successful_ownership_access)
      successful_ownership_access
    else
      response.should be_success
    end
  end
end

关于ruby-on-rails - Rails、Restful Authentication 和 RSpec - 如何测试需要身份验证的新模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64827/

相关文章:

ruby-on-rails - Rails5 中似乎 sidekiq 不支持 actioncable ?

ruby-on-rails - 如何使FactoryGirl.create影响另一条记录的属性?

ruby-on-rails - 在 RSpec 中比较十进制值的正确方法

ruby-on-rails - RSpec,期望随着多个值的变化而变化

javascript - 下拉字段仅显示可用的唯一整数 Rails

ruby-on-rails - RoR,从模块调用列名

ruby-on-rails - Sublime 作为我在 Windows 盒子上的默认编辑器打开空白文件?

angular - 如何在 Angular 6 中测试模板驱动的表单

scala - CallingThreadDispatcher 有什么作用?

linux - 如何在 bash 中测试程序? (功能测试)