两个规格如何共享相同的"它"块?

时间:2016-12-15 02:28:02

标签: ruby rspec-rails

我有两个非常相似的测试。实际上,两种测试都应该产生相同的结果,但是对于不同的输入。每个都需要自己的before块,但为了干,我希望他们共享相同的it块。

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:3)

辅助方法。 (请原谅这个例子的可怕性。如果你发布你的例子会更好: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

答案 2 :(得分:1)

获取块并创建外部方法

例如我有一些测试要求我登录我的应用程序。所以我有一个helper.rb文件,我在每个规范中都包含这个文件,其中包含一个"登录"块。然后在每个测试中我都可以调用login