steve.clarke
steve.clarke

Reputation: 355

How do I test a nested Ruby on Rails controller with RSpec?

I have a Rails controller named PagesController that is nested as follows in app/controllers/sevenpages/public/pages_controller.rb:

module Sevenpages
  module Public
    class PagesController < ApplicationController
      layout nil
      def show 
      end
    end
  end
end

I want to test this controller using RSpec

When I create the following test in spec/controllers/sevenpages/pubic/pages_controller_spec.rb:

require 'spec_helper'

describe Sevenpages:Public::PagesController do
  describe 'GET #show' do
    get :show, use_route: :sevenpages
    {{ tests go here }}
  end
end

I get the following error:

undefined method `get' for #<Class:0x007fe5c88e4300> (NoMethodError)

Now I understand what this error message means. The problem is that the RSpec::Rails::ControllerExampleGroup methods aren't being automatically included in the controller test, so the standard Rails methods such as get, post, etc. aren't available in the test.

I've tried all the recommended solutions that I can find without luck. Here's what I've tried:

I'm at a loss as to what else I can try. I should note that I'm using:

My app is a Rails engine, thus the use_route parameter to the get method.

The only thing I can think of is that RSpec doesn't know how to handle a controller that's nested this deeply. Is there some syntax that I should be aware of to enable RSpec to properly parse this as a controller test?

Upvotes: 2

Views: 518

Answers (1)

Pete
Pete

Reputation: 18075

The code you posted above has the test in a describe block. Typically with Rspec you put the test in a "it" block. Like:

describe Sevenpages:Public::PagesController do
  describe 'GET #show' do
    it 'should work' do
      get :show, use_route: :sevenpages
      {{ tests go here }}
    end
  end
end

If you try this does the method become properly defined?

Upvotes: 3

Related Questions