2011-03-08 41 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

相關問題