2010-03-09 52 views
5

如何在Rspec中測試數據庫視圖?每個場景都被封裝在一個事務中,並且數據看起來並不像它被持久化到數據庫(在我的情況下是MySQL)。我的視圖返回一個空的結果集,因爲沒有記錄在事務中被持久化。我正在通過在規範中設置調試點並在規範正在調試時用數據庫客戶端檢查我的數據來驗證記錄未被存儲。Rspec>測試數據庫視圖

我認爲能讓我的視圖工作的唯一方法是,如果我可以在場景結束之前提交事務,然後在場景完成後清除數據庫。有誰知道如何做到這一點或有沒有更好的方法?

謝謝

回答

2

我想我明白了。爲了不使用交易,您需要指定:

self.use_transactional_fixtures = false 

您還必須確保清理在每個方案後創建的內容。

describe Attendee do 
    self.use_transactional_fixtures = false 

    def clear_all 
    ActiveRecord::Base.connection.execute('delete from users') 
    ActiveRecord::Base.connection.execute('delete from contact_info') 
    ActiveRecord::Base.connection.execute('delete from events') 
    end 

    before(:each) do 
    # create some test users 
    @event = Factory.create(:event) 
    @event.publish! 
    @user = Factory.create(:user) 
    @user_2 = Factory.create(:user_2) 
    end 

    after(:each) do 
    clear_all 
    end 

    it "should list have attendees in the directory" do 
    # in my case, Attendee class uses my attendees database view 
    Attendee.count.should be 2 
    end 
end