Search code examples
ruby-on-railsrubyrspec-railsrspec3

How to write controller spec for method which returns an object, but without checking for any related templates


I would like to ask my question in more conslidated way with basic example.

1) I have UsersController
2) I have show method in it
3) But I don't have any templates for this method(either - show.html.erb/show.xml.erb etc)
4) So currently, I just wanted to write a spec for just checking whether my method is returning an object or not
5) it is working, but as it is CRUD related method, it is expecting a Template for it.
6) ActionView::MissingTemplate

I have tried in this way

it "should show the user record" do
  get :show, :id => 1
  User.should_receive(:find).at_least(:once).with(1).and_return(mock_user)
end
class UsersController
  def show
    # params = {}
    # params = {:id => 1}
    @user_obj = User.find(params[:id]) # ActiveRecord::Relation
  end
end

require 'spec_helper'

describe UsersController do
  def mock_user(stubs={})
    @mock_user ||= mock_model(User, stubs).as_null_object
  end

  it "should show the user record" do
    expect(assigns(:user_obj)).to eq(mock_user) # How to stop execution  here only.
  end
end

ActionView::MissingTemplate: Missing template users/show with {:handlers=>[:erb, :rjs, :builder, :rhtml, :rxml], :formats=>[:html], :locale=>[:en, :en]} in view paths "#"


Solution

  • What you are trying to do doesn't seem right for me. This type of testing (controller tests is) for testing the response of action and rendering. so you shouldn't do that you should test the output of the rendering of the action. otherwise, if you wanted to test the method show only (unit testing) don't use get here you can do this

    users_controller = UsersController.new
    users_controller.show 
    

    and test it as any method inside any class