tin tin
tin tin

Reputation: 372

RSpec error "undefined method `respond_with'..."

I am following the tutorials http://apionrails.icalialabs.com/book/chapter_three But when I ran the controller test bundle exec rspec spec/controllers I am getting undefined method error:

Failures:

 Api::V1::UsersController GET #show 
 Failure/Error: it { should respond_with 200 }
 NoMethodError:
   undefined method `respond_with' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_1:0x00000005d6f650>
 # ./spec/controllers/api/v1/users_controller_spec.rb:17:in `block (3 levels) in <top (required)>'

 Finished in 0.08435 seconds
 2 examples, 1 failure

Please help

Edit: The below is the contents of my spec file

users_controller_spec.rb

require 'spec_helper'

describe Api::V1::UsersController do
  before(:each) { request.headers['Accept'] = "application/vnd.marketplace.v1" }

  describe "GET #show" do
    before(:each) do
      @user = FactoryGirl.create :user
      get :show, id: @user.id, format: :json
    end

    it "returns the information about a reporter on a hash" do
      user_response = JSON.parse(response.body, symbolize_names: true)
      expect(user_response[:email]).to eql @user.email
    end

    it { should respond_with 200 }
  end
end

Upvotes: 6

Views: 3697

Answers (5)

Rokibul Hasan
Rokibul Hasan

Reputation: 4156

Having this error after upgrade my old rails app to rails 5.0. then add the following configuration into spec_helper.rb and now its working fine.

Shoulda::Matchers.configure do |config|
   config.integrate do |with|
     with.test_framework :rspec
     with.library :rails
   end
end

Upvotes: 3

Swaps
Swaps

Reputation: 1548

Here since we are dealing with response codes you can use-

it { expect(response).to have_http_status(200) }

instead of it { should respond_with 200 }

Here no need of shoulda-matchers gem as well.

Ref - https://www.relishapp.com/rspec/rspec-rails/docs/controller-specs

Upvotes: 7

peter
peter

Reputation: 51

I had the same problem and solved it. It looks like using older version of shoulda-matchers helps. I changed the Gemfile to gem "shoulda-matchers", "~>2.5"

Upvotes: 5

Paul A Jungwirth
Paul A Jungwirth

Reputation: 24551

If you're not finding shoulda methods, I'd make sure you have this in your rails_helper.rb or spec_helper.rb:

config.include(Shoulda::Matchers::ActionController, { type: :model, file_path: /spec\/controllers/})

Or it might be there but commented-out.

Upvotes: 2

Gimmy
Gimmy

Reputation: 51

This seems to be an error from shoulda-matchers gem, try to update to the latest version.

Also make sure that it comes after RSpec in your gemfile

group :development, :test do
  gem 'rspec-rails'
  gem 'shoulda-matchers'
end

Upvotes: 0

Related Questions