Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rspec > testing database views

How can database views be tested in Rspec? Every scenario is wrapped in a transaction and the data does not look like it is being persisted to the database (MySQL in my case). My view returns with an empty result set because none of the records are being persisted in the transaction. I am validating that the records are not being stored by setting a debug point in my spec and checking my data with a database client while the spec is being debugged.

The only way I can think to have my view work would be if I could commit the transaction before the end of the scenario and then clear the database after the scenario is complete. Does anyone know how to accomplish this or is there a better way?

Thanks

like image 341
Sean McCleary Avatar asked Mar 09 '10 08:03

Sean McCleary


People also ask

Is RSpec BDD or TDD?

RSpec is a testing tool for Ruby, created for behavior-driven development (BDD). It is the most frequently used testing library for Ruby in production applications. Even though it has a very rich and powerful DSL (domain-specific language), at its core it is a simple tool which you can start using rather quickly.

Does RSpec clean database?

I use the database_cleaner gem to scrub my test database before each test runs, ensuring a clean slate and stable baseline every time. By default, RSpec will actually do this for you, running every test with a database transaction and then rolling back that transaction after it finishes.


1 Answers

I think I got it. In order to not use transactions, you need to specify:

self.use_transactional_fixtures = false

You also must be sure to clean up what you create after each scenario.

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
like image 85
Sean McCleary Avatar answered Oct 16 '22 05:10

Sean McCleary