jmolina
jmolina

Reputation: 269

Rspec controller basic test

I'm working on a ruby on rails project (rails 3.2.12 and ruby 1.9.3) and I'm trying to test one of my controllers. So, I have this controller:

class PostsController < ApplicationController
  def index
    @posts = Post.all
  end
end

and my test:

require "spec_helper"

describe PostsController do
  let(:post){FactoryGirl.create(:post)}
    context "JSON" do
      describe "GET #index" do
        it "should access index" do
           get :index
        end
      end
   end
end

and my routes.rb

 AuthApp::Application.routes.draw do
   resources :posts
 end

but after run

$ rspec spec

I got this error:

1) PostsController JSON GET #index should access index
     Failure/Error: get :index
     ActionView::MissingTemplate:
       Missing template posts/index, application/index with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :jbuilder]}. Searched in:
         * "#<RSpec::Rails::ViewRendering::EmptyTemplatePathSetDecorator:0x007fbfb62d64a0>"
     # ./spec/controllers/post_controller_spec.rb:9:in `block (4 levels) in <top (required)>'

How can access to /posts with index action instead of /posts/index?

Thanks in advance,

Upvotes: 1

Views: 3789

Answers (3)

bosskovic
bosskovic

Reputation: 2054

By default, rspec is configured not to render the views (see here) It can be changed in spec/support/spec_helper.rb (or spec/support/rails_helper.rb) like this:

RSpec.configure do |config| 
  config.render_views = true 
end

or the block can be added in the spec files where needed:

require 'rails_helper' 

RSpec.configure do |config| 
  config.render_views = true 
end 

describe SessionsController, :type => :controller do 
... 

Upvotes: 4

jmolina
jmolina

Reputation: 269

Thanks for all your answers. The problem I had was that my template was a jbuilder template and spec doesn't render them by default.

I was fixed using this link in github.

Upvotes: 1

junil
junil

Reputation: 768

Specify the format as json

it "........" do
 expected = {...}.to_json
 get :index, :format => :json
 response.body.should == expected
end

Upvotes: 2

Related Questions