author avatar

syedsibtain

Mon Jan 13 2025

Shared Context in RSpec

Shared Context: A shared context in RSpec is a way to define common setup code that can be reused across multiple test examples or groups. Instead of duplicating setup code, we define it once in a shared context and include it wherever needed. It helps keep our tests DRY.



RSpec.shared_context "user and post setup", shared_context: :metadata do
  let(:user) { User.create(name: "Alice") }
  let(:post) { Post.create(title: "First Post", user: user) }
end

RSpec.describe "Using shared context in tests" do
  include_context "user and post setup"

  it "has a user with a name" do
    expect(user.name).to eq("Alice")
  end

  it "has a post with a title" do
    expect(post.title).to eq("First Post")
  end
end


In the example, the shared context user and post setup defines let variables for a user and a post.
By including the shared context with include_context, we gain access to those let variables in the test examples.

#rspec #rubyonrails