测试的种子数据

时间:2015-07-30 01:25:33

标签: ruby-on-rails ruby rspec

我需要为我的测试提供一些地理数据,我不确定我是否采取了正确的方法,但这是我尝试过的方法。

在我的规范助手中:

config.before(:each, location_data: true) do |example|
  address = FactoryGirl.create(:address, atitude: 20.9223, longitude: -72.551)
end

我创建的特定地址点。然后我有这些,我认为这会破坏我的数据:

config.before(:suite) do
    DatabaseCleaner.strategy = :truncation
    DatabaseCleaner.clean_with(:truncation)
  end

  config.before(:each) do
    DatabaseCleaner.start
  end

  config.after(:each) do
    DatabaseCleaner.clean
  end

然后在我的测试中我有这个:

context 'nearby', location_data: true do
      context 'there should be 0 matches in radius' do
         binding.pry
         #When I debug here there are 0 addresses created
         expect(Address.count).to eq(1)
      end 
 end

当我查看测试日志时,我的测试数据设置甚至没有被执行,我在这里做错了什么?我需要这个地址用于各种测试,不仅仅是一个而是许多复杂的场景,我会在另一个测试中重用这些地址,这就是为什么我把它们放在一个rspec配置中以使它更干燥

根据最高答案建议进行更改:

module LocationData
  extend ActiveSupport::Concern

  included do
    let!(:address) { FactoryGirl.create(:address, latitude: 20.9223, longitude: -72.551) }
  end
end

然后在我的测试中:

require 'support/location_data'

describe MyModel do
  include LocationData

  context 'nearby' do
      context 'there should be 1 matches in radius' do
         binding.pry
         #When I debug here there are 0 addresses created
         expect(Address.count).to eq(1)
      end 
  end
end

当我计算地址时仍然得到0地址计数。不知道我做错了什么。

解决方案(感谢最大):

我在上下文块中忽略了它:

context 'there should be 1 matches in radius' do
             binding.pry
             #When I debug here there are 0 addresses created
             it 'has one address before' do
               expect(Address.count).to eq(1)
             end
          end 

1 个答案:

答案 0 :(得分:1)

一个好的测试套件将在每个示例之间清空数据库。

为什么?将大量数据填入您的数据库,然后对相同的数据库数据运行一些测试听起来就像一个好主意。但是,如果你测试改变这些数据,你很快就会遇到可能导致扑动测试和严重问题的订购问题。它是一种经过测试和发现缺乏的方法。

相反,您需要为每个测试提供干净的平板。 DatabaseCleaner就是这么做的。它不会破坏您的数据 - 它会让您的数据不会破坏您的测试套件或理智。

您永远不想在rspec配置中创建测试数据。使用它来设置运行测试所需的工具。如果你开始创建一堆标志来设置配置中的数据,它将很快失控。并且您并不需要像您想象的那样经常使用完全相同的数据。

相反,如果您发现自己在规范中重复设置相同的数据,则可以使用示例组将其干掉。或者使用FactoryGirl创建命名工厂。

module GeocodedExampleGroup
  extend ActiveSupport::Concern
  included do
    let(:address) { FactoryGirl.create(:address, latitude: 20.9223, longitude: -72.551) }
  end
end
require 'rails_helper'
require 'support/example_groups/geocoded'

describe SomeModel do
  include GeocodedExampleGroup

  # ...
end
相关问题