Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rspec post :create 'unknown keyword: '

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.

like image 466
Darkisa Avatar asked Oct 10 '17 21:10

Darkisa


1 Answers

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.

like image 77
André Guimarães Sakata Avatar answered Nov 19 '22 09:11

André Guimarães Sakata