【问题标题】:Rails 3 Rspec test database persistsRails 3 Rspec 测试数据库持续存在
【发布时间】:2011-07-11 02:39:13
【问题描述】:

我的测试数据库在每次运行后都没有擦除数据时遇到问题。我也有黄瓜测试,每次运行时都会清除数据库。

以下规范测试仅在 rake db:test:prepare 之后立即起作用,我的测试或导致数据持续存在的 spec_helper.rb 是否有问题?

我的规格测试是:

require "spec_helper"

describe "/api/v1/offers", :type => :api do
  Factory(:offer)
  context "index" do
    let(:url) { "/api/v1/offers" }
    it "JSON" do
      get "#{url}.json"
      last_response.status.should eql(200)
      last_response.body.should eql(Offer.all.to_json(:methods => [:merchant_image_url, :remaining_time, :formatted_price]))
      projects = JSON.parse(last_response.body)
      projects.any? { |p| p["offer"]["offer"] == "Offer 1" }.should be_true
    end

    it "XML" do
      get "#{url}.xml"
      last_response.body.should eql(Offer.all.to_xml(:methods => [:merchant_image_url, :remaining_time, :formatted_price]))
      projects = Nokogiri::XML(last_response.body)
      projects.css("offer offer").text.should eql("Offer 1")
    end
  end
end

我的 spec/spec_helper.rb 文件如下所示:

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

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

RSpec.configure do |config|
  config.mock_with :rspec


  config.fixture_path = "#{::Rails.root}/spec/fixtures"

  config.use_transactional_fixtures = true
end

干杯, 加兹勒。

【问题讨论】:

    标签: ruby-on-rails-3 rspec


    【解决方案1】:

    将 'Factory(:offer)' 移至规范本身 - 'it' 块。

    【讨论】:

    • 谢谢,这行得通有没有办法在 it 块之外创建它,这样我只需要调用 Factory(:offer) 一次?
    【解决方案2】:

    工厂需要进入before(:each)区块:

    describe "/api/v1/offers", :type => :api do
      before(:each) do
        Factory(:offer)
      end
      context "index" do
        ... etc ...
    

    RSpec 将在每个示例运行后回滚在 before(:each) 块中创建的所有行。

    【讨论】:

    • 非常感谢,这就是我所追求的。
    【解决方案3】:

    显然 rspec 不会清除 FactoryGirl 创建的对象。一种流行的方法是根据需要截断表。请参阅here 和线程here 了解更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-28
      • 1970-01-01
      • 2011-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-28
      相关资源
      最近更新 更多