Guu
Guu

Reputation: 961

Rspec fields in context scope

Didn't really know how to phrase the title but my problem is as follows:

shared_examples "something" do 
  context "for something" do 
    fields.each do |field| 
      it "should have #{field} field" do 
        #Check something 
      end
    end
  end
end

describe Clazz do
  it_behaves_like "something" do
    let(:fields) {%w{something something2}}
  end
end

The execution of course blows up in the fields.each part since the variables are introduced in the it scope, not in context.

So my question is how would I introduce variables with to it_behaves_like to the context scope? Or should I use something else.

Upvotes: 0

Views: 187

Answers (3)

David Chelimsky
David Chelimsky

Reputation: 9000

shared_examples already creates a new context, so I think the cleanest way would be like shioyama's example without the extra context:

shared_examples_for "something" do |fields|
  fields.each do |field| 
    it "should have #{field} field" do 
      # specify something
    end
  end
end

describe Clazz do
  it_behaves_like "something", %w{something something2}
end

Upvotes: 2

Chris Salzberg
Chris Salzberg

Reputation: 27374

Don't know about shared_examples, but if you use shared_examples_for you can pass arguments to the block, like so:

shared_examples_for "something" do |fields|
  context "for something" do
    fields.each do |field| 
      it "should have #{field} field" do 
        #Check something 
      end
    end
  end
end

describe Clazz do
  it_behaves_like "something", %w{something something2}
end

Upvotes: 2

peakxu
peakxu

Reputation: 6675

Let is evaluated before each it block but not for context or describe as far as I'm aware of.

describe "something" do 
  let(:fields) { %w{something something2} }

  it "should have all fields" do 
    fields.each do |field| 
    end
  end
end

Upvotes: 0

Related Questions