我有两个非常相似的测试。事实上,两种测试都应该产生相同的结果,但是对于不同的输入。每个需要自己的before
块,但为了DRY的利益,我希望他们分享相同的it
块。两个规格如何共享相同的“it”块?
这可能吗?如果是这样,怎么样?
我有两个非常相似的测试。事实上,两种测试都应该产生相同的结果,但是对于不同的输入。每个需要自己的before
块,但为了DRY的利益,我希望他们分享相同的it
块。两个规格如何共享相同的“it”块?
这可能吗?如果是这样,怎么样?
辅助方法。 (对不起例子的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
拿块,创造和外部方法
例如我有一些测试,要求我登录到我的应用程序。所以我有一个helper.rb
文件,我在每个规范中包含并包含“登录”块。然后在每次测试中我都可以拨打login
共享的例子是设计用于此目的。您可以将常见的it
块保留在共享示例中,并将其包含在describe或context块中。
最简单的例子是,
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)
挂钩和嵌套contexts
或describe
。
欲了解更多,你可以看看rspec documentation。