工厂女孩对象在测试后未被丢弃.请查看我的测试设置



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

spec/support/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

spec/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
config.use_transactional_fixtures = false

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

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

相关内容

最新更新