组合多个let语句

时间:2014-02-20 09:53:40

标签: rspec

如何定义允许我而不是写

的方法create_all
describe "some spec" do
  let(:a) { create :a }
  let(:b) { create :b, :a => a }
  ...

describe "some spec" do
  create_all
  ...

更具体地说:哪里我是否必须定义它以便能够在describe上下文中使用它?

它应该适用于不同的spec文件。

4 个答案:

答案 0 :(得分:5)

RSpec中有一种机制可以做到这一点,它是shared_context。它简单,优雅,不需要跳过箍,因为其他一些选项需要你去做。

因此,在您的示例中,您将设置共享上下文:

# spec/support/create_all.rb

shared_context "create all" do
  let(:a) { create :a }
  let(:b) { create :b, :a => a }
  ...
end

然后在您的规格中

# some_spec.rb

describe "some spec" do
  include_context "create all"

  it "tests something" do
    ...
  end
end

进一步阅读:

答案 1 :(得分:1)

关键是在config.include中使用config.extend代替spec/spec_helper.rb。 首先,我们创建一个模块DescribeHelper

module DescribeHelper
  def create_all
    let(:a) { create :a }
    let(:b) { create :b, :a => a }
  end
end

在spec / support / describe_helper.rb内部

然后,我们必须在spec/spec_helper.rb内进行

...

RSpec.configure do |config|
  ...
  config.extend  DescribeHelper
  ...
end

...

这将导致create_all块内describe可用。

答案 2 :(得分:0)

我认为你可以将方法定义放在这个文件的任何地方(甚至在其他文件夹中 - 例如spec/support)但是在it块之外。并且需要在测试中触发(例如在before块中)。

describe "class" do

  def create_all
    ...
  end

  describe "method" do
    before { create_all }

    it '' do
    end

    it '' do
    end

end

PS你提到你想在create_all上下文中使用describe。我认为这是不可能的,因为(我相信)RSpec解析规范文件并只运行必要的代码:所有before块,所有let!等.RSpec不执行其他东西

PPS 据我所知,你想使用延迟加载。这只是一个可能对你有帮助的想法。你可以

  1. 使用创建数据的方法在spec/support中创建一个模块。

  2. 在您的测试文件中包含您的模块(例如user_spec.rb) - 现在应该在此文件中提供已定义的方法

  3. 在测试中使用这些方法。

  4. 我认为行为应该类似于延迟加载。您可以使用不同规范中的方法(只包括模块)

答案 3 :(得分:0)

spec/support目录

下创建模块
module ApplicationMacros
  def create_all
    a = create(:a)
    b = create(:b, a: a)
  end
end

将其放在spec/spec_helper.rb

Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}

最后从您create_all阻止

致电describe
describe "some spec" do
  before :all do      
   create_all
  end
  .........
end

about-spec-support

check this