在rspec2中重写共享示例组

时间:2011-02-23 23:43:49

标签: ruby rspec rspec2

在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中编写它?

1 个答案:

答案 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相关。