首页 > 解决方案 > 如何将一个大的 rspec 文件分成更小的部分

问题描述

因此,在我的项目中,我使用 cancancan 进行授权。对于编写能力规范,我们在ability_spec.rb 中维护。从过去几年开始,文件大小已经大大增加。现在它有大约 3000 行,这几乎是我们面临的主要问题是我们无法一次运行整个文件。如果我们尝试这样做,我们的系统就会冻结。为了解决这个问题,我想出了将文件分成多个文件的方法。因为,rspec 遵循命名约定,所以我有点困惑如何继续它。

class Ability
  include CanCan::Ability
  attr_accessor :feature_factory
  def initialize(user, session = nil)
    alias_action :read, :update, :to => :read_write
    user ||= User.new # guest user (not logged in)


    can :read, Abc
    can :manage, :file
    can :view, :login

    if user.anonymous_user?
      ## a lot of abiities
    end

    if user.mum_user?
       ## a lot of abiities
    end

    if user.tsm_user?
       ## a lot of abiities
    end

   #Similarly we have a lot of roles and abilities
end

require 'spec_helper'
require "cancan/matchers"


describe Ability do
  describe "#anonymous_user" do
    ## a lot of specs for testing
  end

  describe "#tsm_user" do
     ## a lot of specs for testing
  end

  describe "#mum_user" do
     ## a lot of specs for testing
  end

  # similarly for other user roles

end

能力文件路径 - app/models/ability.rb

能力规格文件路径 - spec/models/ability_spec.rb

所以,到目前为止,我试图在 spec/models 中创建一个能力文件夹,并根据各自文件中的角色划分规范。像下面的东西

spec/models/ability/anonymous_user_spec.rb
require 'spec_helper'
require "cancan/matchers"

describe Ability do
  describe "#anonymous_user" do
    ## a lot of specs for testing
  end
end

spec/models/ability/tsm_user_spec.rb
require 'spec_helper'
require "cancan/matchers"

describe Ability do
  describe "#tsm_user" do
    ## a lot of specs for testing
  end
end

spec/models/ability/mum_user_spec.rb
require 'spec_helper'
require "cancan/matchers"

describe Ability do
  describe "#mum_user" do
    ## a lot of specs for testing
  end
end

当我尝试运行它时,它没有给我任何错误,它在一秒钟内运行。此外,我试图引入一个错误审议,但它并没有失败。所以,我的问题是

1)当文件很大时如何解决此类问题

2)如果上述方法是正确的,那么为什么它对我不起作用

3)如果我分割文件会有任何性能提升

标签: ruby-on-railsrubyrspecruby-on-rails-5.2cancancan

解决方案


  1. 拆分大规格文件听起来是个好主意。在巨大的规范文件中导航是一场噩梦。然而,问题转移到维护多个规范文件(这可能仍然不那么邪恶)。
  2. 据我所知,由于测试数据库问题,它对您不起作用。你解决了,对吧?
  3. 如果您运行并行规范,您可能会看到小的性能提升。它不会在 1 个线程中运行 1 个长规范,而是并行运行较小的规范。如果你不并行运行它,它不会给你任何性能改进。

推荐阅读