Search code examples
ruby-on-railsrubytddcontrollersrspec-rails

run database with rspec-rails


I am trying to test a controller with RSpec but am having a problem because a function in the controller requires a database.

the line of code in the controller looks something like:

@myallresources = Myrsources.all

where Myresources just inherits from ActiveRecord::Base

however, because there is no database, there is nothing to load and @myallresources is just an empty array, causing the test to fail. Is there a way to connect to a database while running the rspec?

I am very new to RSpec and rails so any help would be very appreciated. Thanks.


Solution

  • You shouldn't use a database connection in your controller specs.

    Check the section about database isolation on this page http://rspec.info/rails/writing/controllers.html

    Basically you have to mock or stub your ActiveRecord models, as those should be tested separately in the models specs. Here's a simple example using mock_model:

    before do
      mocks = (1..3).map { mock_model(MyResource) }
      MyResource.should_receive(:all).and_return(mocks)
    end
    

    Put this inside the same block where reside the describe definition testing for the actions that use MyResource.all.

    You can find good explanation of mocks and stubs in following links: