2016-12-15 61 views
0

我有两个非常相似的测试。事实上,两种测试都应该产生相同的结果,但是对于不同的输入。每个需要自己的before块,但为了DRY的利益,我希望他们分享相同的it块。两个规格如何共享相同的“it”块?

这可能吗?如果是这样,怎么样?

回答

3

辅助方法。 (对不起例子的horribleness会更好,如果你想发布你的:P)

describe "soup" do 
    def soup_is_salty  # helper method! \o/ 
    soup.add(:meat) 
    soup.add(:egg) 
    soup.cook 
    soup.salty? 
    end 

    describe "with carrot" do 
    before(:all) do 
     soup.add(:carrot) 
    end 

    it "should be salty" do 
     soup_is_salty  # get help from helper method! \o/ 
    end 
    end 

    describe "soup with potato" do 
    before(:all) do 
     soup.add(:potato) 
    end 

    it "should be salty" do 
     soup_is_salty  # get help from helper method! \o/ 
    end 
    end 
end 
1

拿块,创造和外部方法

例如我有一些测试,要求我登录到我的应用程序。所以我有一个helper.rb文件,我在每个规范中包含并包含“登录”块。然后在每次测试中我都可以拨打login

4
在Rspec的

共享的例子是设计用于此目的。您可以将常见的it块保留在共享示例中,并将其包含在describe或context块中。

shared_examples的

最简单的例子是,

RSpec.shared_examples "unauthorized_response_examples" do 
    it { expect(subject).to respond_with(403) } 
    it { expect(json['message']).to eq(I18n.t("unauthorized")) } 
end 

,每当你需要检查未授权的响应可以包括像例子控制器的规格内,

... 
include_examples "unauthorized_response_examples" 

此外,您还可以传递参数,动作名称和控制器名称,并具有before(:each|:all)挂钩和嵌套contextsdescribe

欲了解更多,你可以看看rspec documentation

相关问题