2017-08-30 93 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