2011-03-08 39 views
10

我遇到了一个问题,我的测试数据库没有在每次运行后擦除数据。我也有黄瓜测试,每次运行这些数据库时都会清除数据库。Rails 3 Rspec测试数据库持续存在

以下规范测试只能在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_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 

干杯, Gazler。

回答

16

工厂需要在before(:each)块去:运行每个示例后

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

的RSpec将回滚在before(:each)块创建的任何行。

+0

非常感谢,那是我以后的事。 – Gazler 2011-03-08 19:58:30

2

将'Factory(:offer)'移动到规格本身 - 'it'块。

+0

谢谢,工作是否有任何方法可以让它在块外创建,这样我只需要调用Factory(:offer)一次? – Gazler 2011-03-08 13:45:30

3

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

相关问题