2017-08-30 129 views
0

如何在RSpec中定义当前范围的主题(改进主题)时访问父范围的主题?访问RSpec中的父范围主题?

示例代码:

describe MyModule.method(:some_method) do 

    context "when called with a String" do 
    let(:string) { "Hey there!" } 

    # I want to refine the subject using the parent scope's subject - common case 
    # is applying a subject method. Something like: 
    subject { super.subject.call string } 

    # Use subject... 

    end # when called with a String 

end # MyModule.some_method 
+0

就快成功了:'{主题超()}'即可。 – mudasobwa

+0

@mudasobwa真的吗?我会回去再试一次,但是我发誓我在那里有'super.call'(应该和super()。call')一样,并且它不工作... – nrser

+0

@mudasobwa呵呵, super()。call' works('super.call' does not)... weird ...我想我不完全理解'super',我认为这是一个方法调用?无论如何,非常感谢! – nrser

回答

0

OK,信贷从上述评论@mudasobwa,这里的解决方案:

你需要调用super()明确没有参数 - super不会单独工作,因为它试图使用Ruby的隐式传递参数并失败。

更正例如:

describe MyModule.method(:some_method) do 

    context "when called with a String" do 
    let(:string) { "Hey there!" } 

    # Note the explicit `()`: 
    subject { super().call string } 

    # Use subject... 

    end # when called with a String 

end # MyModule.some_method 
0

你能说出你的主题:

context do 
    subject(:my_thing) { described_class.new } 

    context '#do_stuff' 
    subject { my_thing.do_stuff } 

    it { expect(subject).to ... } # or 
    it { is_expected.to ... } 
    end 
end 
+0

[文档](https://relishapp.com/rspec/rspec-core/v/3-6/docs/metadata/described-class)似乎暗示只有在最外层的主题是类时才应用'describe_class'(在这种情况下它是一种方法)。无论如何,我想我想用'subject'来简化共享示例而不用传递参数。 – nrser