2011-02-23 28 views
1

在rspec的1 I能做重写共享示例组中rspec2

describe "Something", :shared => true do 
include SomeModule # which has the :a_method method 

def a_method(options) 
    super(options.merge(:option => @attr) 
end 

it "foofoofoo" do 
end 
end 

describe "Something else" do 
    before(:each) do 
    @attr = :s_else 
    end 

    it_should_behave_like "Something" 

    it "barbarbar" do 
    a_method(:name => "something else") 
    Something.find("something else").name.should == "Something else" 
    end 
... 
end 

即,我可以使用:shared => true不仅重构的例子,但也共享方法的定义和属性。我意识到这个例子是人为设计的,但是如何在不触及SomeModule模块或Something类的情况下将它写入rspec> = 2?

回答

2

您可以shared_examples_for

shared_examples_for "something" do 
    include SomeModule # which has the :a_method method 

    def a_method(options) 
    super(options.merge(:option => @attr)) 
    end 

    it "foofoofoo" do 
    end 
end 

做到这一点,与it_behaves_like拨打:

it_behaves_like "something" 

编辑

若昂正确地指出,这不包括在实例SomeModule描述块。包括必须在共享示例组之外进行,例如,在该规范文件的顶部

include SomeModule # which has the :a_method method 

# ... 

shared_examples_for "something" do 
    def a_method(options) 
    super(options.merge(:option => @attr)) 
    end 

    it "foofoofoo" do 
    end 
end 

大卫赫利姆斯基讨论的在RSpec的2共享其实例可以在this blog post是恰当的一些新的特点。

+0

是的,但在声明'it_behaves_like'的示例组的示例中,我无法调用'a_method'。换句话说,你可以在你的答案中加入“barbarbar”例子吗? – 2011-02-24 11:57:57

+0

看我的编辑。博客文章很好阅读,可能有助于你的情况。我发现很难遵循你的意图 - 也许如果你“去混淆”了这些例子,他们可能会更清楚。 – zetetic 2011-02-24 20:34:35

+0

感谢您的博客文章。你完全正确,没有理由对这个混淆,我试图转换的完整例子是开源的,并在https://github.com/gma/nesta/blob/master/spec/models_spec找到。 RB。 “something”是“Page”示例组。 “减价页面”和“HAML页面”以及两种“别的东西”。 – 2011-02-27 02:22:25