0

我需要为我的单元测试设置不同的设置,为我的集成测试设置不同的设置。例子

对于单元测试,我想做

WebMock.disable_net_connect!(:allow_localhost => true)

对于集成测试,我想做

WebMock.allow_net_connect!

另外,在开始集成测试之前,我想确保 solr 已启动。因此我希望能够打电话

config.before(:suite) do
  SunspotStarter.start
end

但是,仅用于集成测试。如果它是一个单元测试,我不想启动我的 solr。

如何保持它们的配置分开?现在,我通过将集成测试保存在 spec 文件夹之外的文件夹中解决了这个问题,该文件夹有自己的 spec_helper。有没有更好的办法?

4

2 回答 2

2

您可以为 before / after 块指定类型,就像为 include 语句指定类型一样。因此,您可以执行以下操作:

RSpec.configure do |config|
  config.before(:each, type: :model) do
    WebMock.disable_net_connect!(:allow_localhost => true)
  end

  config.before(:each, type: :request) do
    WebMock.allow_net_connect!
  end

  config.before(:suite, type: :request) do
    SunspotStarter.start
  end
end
于 2012-05-21T11:06:30.167 回答
2

我的解决方案可能有点老套,但据我测试它应该可以工作。

我注意到这config.include需要type争论,所以它可能是抗体用于执行任意代码块,如下所示:

module UnitTestSettings
  def self.included(base)
    WebMock.disable_net_connect!(:allow_localhost => true)
  end
end

module IntegrationTestSettings
  def self.included(base)
    WebMock.allow_net_connect!

    RSpec.configure do |config|
      config.before(:suite) do
        SunspotStarter.start
      end
    end

  end
end

Rspec.configure do |config|
  config.include UnitTestSettings, :type => :model
  config.include IntegrationTestSettings, :type => :integration
end

将它放在支持文件夹中的文件中,您应该一切顺利,尽管我还没有实际测试过代码。另外,我很确定有更好的方法来实现同样的目标。

于 2011-01-07T11:14:23.313 回答