Skip to content

Instantly share code, notes, and snippets.

@hirakuro
Created September 30, 2011 06:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hirakuro/1252824 to your computer and use it in GitHub Desktop.
Save hirakuro/1252824 to your computer and use it in GitHub Desktop.
module LocalContextFeature
def local_context(name, &block)
raise NameError, "local context `#{name}' is already defined" if find_local_context(name)
@local_contexts ||= {}
@local_contexts[name] = block
end
def include_local_context(name)
lc = find_local_context(name)
if lc
instance_eval(&lc)
else
raise NameError, "local context `#{name}' is not defined"
end
end
def find_local_context(name)
@local_contexts ||= {}
@local_contexts[name] || (superclass.respond_to?(:find_local_context) ? superclass.find_local_context(name) : nil)
end
end
class RSpec::Core::ExampleGroup
extend LocalContextFeature
end
describe LocalContextFeature do
local_context "test 1" do
before do
@v = "t1"
end
end
context "already defined" do
exception = nil
begin
local_context "test 1"
rescue NameError
exception = $!
end
subject { exception }
it { should be_kind_of(NameError) }
its(:message){ should == "local context `test 1' is already defined" }
end
context "include local context" do
include_local_context("test 1")
subject { @v }
it { should == "t1" }
end
context "not defined" do
exception = nil
begin
include_local_context "test 2"
rescue NameError
exception = $!
end
subject { exception }
it { should be_kind_of(NameError) }
its(:message){ should == "local context `test 2' is not defined" }
end
context "add local context in sub class" do
local_context "test 2" do
before do
@v2 = "t2"
end
end
context "use local context" do
include_local_context "test 1"
include_local_context "test 2"
it do
@v.should == "t1"
@v2.should == "t2"
end
end
end
context "context defined at other sub class is not available" do
exception = nil
begin
include_local_context "test 2"
rescue NameError
exception = $!
end
subject { exception }
its(:message){ should == "local context `test 2' is not defined" }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment