在rspec 1中,我可以做到
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中编写它?
答案 0 :(得分: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"
修改强>
Joao正确地指出,这不能包含描述块中的示例的SomeModule。包含必须在共享示例组之外进行,例如在spec文件的顶部
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
David Chelimsky讨论了RSpec 2中共享示例的一些新功能,这些功能可能与this blog post相关。