Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine multiple let statements

Tags:

rspec

How can I define a method create_all that 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
  ...

More specifically: Where do I have to define it in order to be able to use it in the describe context?

It should work across different spec files.

like image 358
Alexander Presber Avatar asked Feb 13 '23 17:02

Alexander Presber


1 Answers

There is a mechanism in RSpec to do this, and it is shared_context. It is simple, elegant and doesn't require jumping through hoops as some of the other options need you to do.

So, in your example you'd set up a shared 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 specs

# some_spec.rb

describe "some spec" do
  include_context "create all"

  it "tests something" do
    ...
  end
end

Some further reading:

  • https://www.relishapp.com/rspec/rspec-core/docs/example-groups/shared-context
  • http://testdrivenwebsites.com/2011/08/17/different-ways-of-code-reuse-in-rspec/
like image 125
Richard Jordan Avatar answered May 31 '23 15:05

Richard Jordan