ruby-on-rails - 如何在多个 RSpec 上下文中使用相同的共享示例和前置过滤器?

标签 ruby-on-rails testing rspec dry before-filter

我有一个非常丑陋的 Controller 规范,看起来像这样:

describe "GET index" do
  context "when authorized" do
    before(:each) do
      sign_in @user
    end

    ...
  end

  include_examples "when unauthorized"
end

describe "GET show" do
  context "when authorized" do
    before(:each) do
      sign_in @user
    end

    ...
  end

  include_examples "when unauthorized"
end

...

有没有办法将之前的过滤器和共享示例移出到每个操作的某种共同特征中?如果没有,是否有任何方法可以完全消除它?

最佳答案

是的,你可以。示例来自:https://www.relishapp.com/rspec/rspec-core/docs/example-groups/shared-examples

require "set"

shared_examples "a collection object" do
  describe "<<" do
    it "adds objects to the end of the collection" do
      collection << 1
      collection << 2
      expect(collection.to_a).to match_array([1, 2])
    end
  end
end

describe Array do
  it_behaves_like "a collection object" do
    let(:collection) { Array.new }
  end
end

describe Set do
  it_behaves_like "a collection object" do
    let(:collection) { Set.new }
  end
end

我要强调的是,每个测试都应该只测试一件事,所以要小心你的编写方式。您还可以将共享内容移动到单独的文件,上面的链接也在共享内容选项卡下显示。

请记住,您希望测试具有可读性。对于像 before 过滤器和登录这样的小代码,我保留了下来。它可能不是 DRY,但对我来说,直接阅读测试比引用单独的示例或文件更容易。如果您有一个需要多次执行的大型测试,将其移出到单独的示例或文件中会更容易。

关于ruby-on-rails - 如何在多个 RSpec 上下文中使用相同的共享示例和前置过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20979123/

相关文章:

ruby - 我如何在页面对象类中使用 Rspec Expectations

ruby-on-rails - 使用嵌套参数从 Node js 到 ruby​​ on Rails 的 http post

javascript - Rails 生成 JSON 对象

testing - 比较 Jenkins CI 中的先前版本和当前版本

JavaScript:在另一个函数调用完成后继续执行函数

ruby - 在 Ruby 中解析 json 文件中的值

ruby - 在 RSpec 中测试模块

ruby-on-rails - 没有这样的文件要加载——rest_client (Rails 3)

html - rails 4 : Change 'name' attribute of Simple Form input

javascript - Jasmine 中的错误预期