在rspec中,将类名传递给shared_example的正确方法是什么?

时间:2014-02-16 21:45:48

标签: rspec

在测试模块的rspec测试套件中,测试用于评估包含该模块的类的行为。下面是一个粗略的例子来说明。

describe "MyMod" do
  module MyMod; end 

  shared_examples_for "a class" do |klass|
    it "includes the module" do
      klass.included_modules.include? MyMod.should be_true
    end 
  end 

  describe "when included in a class" do
    before(:each) { class C; include MyMod; end }
    it_behaves_like "a class", C
  end 

  describe "when extended in a class" do
    before(:each) { class C; extend MyMod; end }
    it_behaves_like "a class", C
  end
end 

我遇到的问题是在C执行时未定义类it_behaves_like,产生错误:

`block (2 levels) in <top (required)>': uninitialized constant C (NameError)

定义类并将其传递给shared_example的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

您遇到的问题是在执行before块之前评估共享示例的参数。您需要将共享示例传递给符号:C并让您的示例将其转换为常量,或者您需要传递一个设置其他变量的块,如https://www.relishapp.com/rspec/rspec-core/v/2-11/docs/example-groups/shared-examples#providing-context-to-a-shared-group-using-a-block