Combine multiple let statements

How can I define a method create_allthat allows me instead of writing

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

to write

describe "some spec" do
  create_all
  ...

In particular: Where do you need to define it in order to be able to use it in context describe?

It should work in different spec files.

+4
source share
4 answers

RSpec has a mechanism for this, and that is shared_context. It is simple, elegant and does not require jumping through hoops, as you need to make some other options.

So, in your example, you set up the general context:

# spec/support/create_all.rb

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

Then in your specifications

# some_spec.rb

describe "some spec" do
  include_context "create all"

  it "tests something" do
    ...
  end
end

Further reading:

+5

config.extend config.include 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.

+1

, ( , 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 spec : before , let! .. RSpec

, . , .

  • spec/support , .

  • (, user_spec.rb) -

  • .

, . ( )

0

create module in directory spec/support

module ApplicationMacros
  def create_all
    a = create(:a)
    b = create(:b, a: a)
  end
end

put it in spec/spec_helper.rb

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

finally call create_allout of you describeblock

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

about-spec-support

check this

0
source

Source: https://habr.com/ru/post/1527861/


All Articles