Rspec post :create 'unknown keyword: '
Asked Answered
A

1

7

I'm new to Rspec and I am trying to test my controller methods for basic functionality. I know I'm not supposed to test basic functionality, but I'm doing it more for learning purposes than to build something.

I have a controller called ProtocolsController. The controller is used for basic CRUD functionality. I am trying to test the controllers #create method. Below is my #create controller:

def create
    @protocol = Protocol.new(protocol_params)

    if @protocol.save
      flash[:notice] = 'New protocol added'
      redirect_back(fallback_location: 'test_results#index')
    else
      flash[:notice] = @protocol.errors[:name]
      render 'new'
    end
  end

To test the sad path, I want to pass to the controller a mock object that contains the necessary parameters for creating an instance of the Protocol class. To do this I have the following code:

  describe '#create' do
    it 'fails to save because the name already exists' do
      params = FactoryGirl.attributes_for(:protocol)
      post :create, :protocol => params
    end
  end 

Now I know the test is incomplete, but I am testing one line at a time and when I run Rspec I get the following error:

Failure/Error: post :create, :protocol => params

     ArgumentError:
       unknown keyword: protocol

But when I change post to: expect { post :create, :protocol => params }

It works. Which brings me to my questions:

  • Why is the first post (post :create, :protocol => params) failing?
  • How would I go about sending a mock object to the controller?
  • Why does the expect version work?

Any insight into the questions will be much appreciated. I've been scratching my head trying to figure this out and my guess is that it's an obvious answer.

Adamandeve answered 10/10, 2017 at 21:40 Comment(2)
What version of the RSpec are you using?Cruel
the latest version -> 3.6Adamandeve
P
17

The way you're calling post does not work anymore in Rails 5.

This is the deprecation warning of the previous version:

ActionController::TestCase HTTP request methods will accept only keyword arguments in future Rails versions.

Now you have to add the params key, like this:

post :create, params: { protocol: params }

Notice that post :create, :params => { :protocol => params } means the same, it's just a different syntax.

Pedagogics answered 10/10, 2017 at 23:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.