FactoryGirl对象在测试后没有丢弃。请查看我的测试设置

时间:2014-08-20 00:55:00

标签: ruby-on-rails rspec

测试运行后,对象会持久存在。我通过进行PowerUp.all.count测试确认,每次运行时计数增加2,这个数字等于每次运行时为测试创建的对象。我不知道我是否误用了FactoryGirl,或者我是否配置了错误的spec_helper。

规格/支持/ factory_girl.rb:

RSpec.configure do |config|
  config.include FactoryGirl::Syntax::Methods
end

规格/ rails_helper.rb:

ENV["RAILS_ENV"] ||= 'test'
require 'spec_helper'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'

Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }

ActiveRecord::Migration.maintain_test_schema!

RSpec.configure do |config|
  config.fixture_path = "#{::Rails.root}/spec/fixtures"
  config.use_transactional_fixtures = false
  config.infer_base_class_for_anonymous_controllers = false
  config.infer_spec_type_from_file_location!
end

规格/ spec_helper.rb:

ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'factory_girl'

RSpec.configure do |config|
config.order = :random

config.before(:all) do
  FactoryGirl.reload
end

  Kernel.srand config.seed

  config.expect_with :rspec do |expectations|
    expectations.syntax = :expect
  end

  config.mock_with :rspec do |mocks|
    mocks.syntax = :expect
    mocks.verify_partial_doubles = true
  end

end

规格/ API / power_up_spec.rb:

describe Api::PowerUpsController, :type => :controller do 

    describe "GET power_ups" do
        it "returns all power-ups" do 
            FactoryGirl.create :power_up, name: "Increase rate of take", description: "You gain points more quickly"
            FactoryGirl.create :power_up, name: "Decrease rate of give", description: "You lose points more slowly"

            get :index, :format => :json

            expect(response.status).to eq 200

            body = JSON.parse(response.body)
            power_up_names = body.map { |m| m["name"] }

            expect(power_up_names).to match_array(["Increase rate of take",
                                               "Decrease rate of give"])
        end

    end

end

1 个答案:

答案 0 :(得分:1)

config.use_transactional_fixtures = false

这将关闭默认行为,即在每个示例之后回滚事务。设置为false时,RSpec不会尝试管理测试数据库。

当RSpec不使用事务时,您可以使用database_cleaner删除测试创建的行。这通常在编写功能规范时使用。