Skip to content

Instantly share code, notes, and snippets.

@dougalcorn
Last active August 29, 2015 14:05
Show Gist options
  • Save dougalcorn/2f953894ba70a7af9109 to your computer and use it in GitHub Desktop.
Save dougalcorn/2f953894ba70a7af9109 to your computer and use it in GitHub Desktop.
rspec contexts

The lets are evaluated from inner-most to outer; but the before are evaluated from outer to inner. With rspec-given the point is to use When as just the bit of code that's "under test". All of the Givens are pre-conditions or setup. That's one of the things I like most about rspec-given, it separates setup code from code under test. The other thing I like about it is the brevity of the individual tests. I find the description on it blocks often quite redundant with the code in the block. I like how Then removes that duplication. Another benefit of rspec-given is that is has natural language failures built in. That's pretty cool.

describe "Context Scoping" do
let(:foo) { "bar" }
before do
@instance_variable = foo
@inner_instance_variable = bar # this might blow up because bar isn't defined in outer scope
end
it "is the outer context" do
# requires :foo to be defined in the outer context because it's tested against here
expect(foo).to eq("bar")
expect(@instance_variable).to eq("bar")
end
context "changing values" do
let(:foo) { "foobar" }
let(:bar) { "barbaz" }
it "uses the inner context" do
expect(@instance_variable).to eq("foobar")
expect(@inner_instance_variable).to eq("barbaz")
end
end
end
describe "Given context scoping" do
Given(:foo) { "bar" }
When do
@instance_variable = foo
@inner_instance_variable = bar
end
Then { expect(foo).to eq("bar") }
Then { expect(@instance_variable).to eq("bar")
context "changing values" do
Given(:foo) { "foobar" }
Then { expect(foo).to eq("foobar") }
And { expect(@instance_variable).to eq("foobar") }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment