两个规格如何共享相同的 "it" 块?
How can two specs share the same "it" block?
我有两个非常相似的测试。事实上,这两个测试应该产生相同的结果,但对于不同的输入。每个人都需要自己的 before
块,但为了 DRY 的利益,我希望他们共享相同的 it
块。
这可能吗?如果是,怎么做?
获取块并创建外部方法
例如,我有一些测试需要我登录到我的应用程序。所以我有一个 helper.rb
文件,我将其包含在每个规范中并且包含一个 "login" 块。然后在每次测试中我都可以调用 login
辅助方法。 (请原谅这个例子太可怕了。如果你发布你的例子会更好: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
Rspec 中的共享示例旨在用于此目的。您可以在共享示例中保留常见的 it
块,并将它们包含在描述或上下文块中。
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)
挂钩和嵌套 contexts
或 describe
。
更多可以看rspec documentation.
我有两个非常相似的测试。事实上,这两个测试应该产生相同的结果,但对于不同的输入。每个人都需要自己的 before
块,但为了 DRY 的利益,我希望他们共享相同的 it
块。
这可能吗?如果是,怎么做?
获取块并创建外部方法
例如,我有一些测试需要我登录到我的应用程序。所以我有一个 helper.rb
文件,我将其包含在每个规范中并且包含一个 "login" 块。然后在每次测试中我都可以调用 login
辅助方法。 (请原谅这个例子太可怕了。如果你发布你的例子会更好: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
Rspec 中的共享示例旨在用于此目的。您可以在共享示例中保留常见的 it
块,并将它们包含在描述或上下文块中。
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)
挂钩和嵌套 contexts
或 describe
。
更多可以看rspec documentation.