Rspec 3.6, Rails 5 error: wrong number of arguments (given 2, expected 1) for `post` request
Asked Answered
R

1

19

I just started a new project in Rails 5, (my first, though I have several projects in Rails 4.x.) and am having trouble with controller specs.

describe RequestsController, :type => :controller do

  it "receives new request" do
    post :accept_request, my_params
  end

end

Returns the error:

 Failure/Error: post :accept_request, my_params

 ArgumentError:
   wrong number of arguments (given 2, expected 1)

I understand there has been a shift in the preferred testing strategy for controllers with Rails 5 as noted on Everyday Rails, specifically, shifting controller tests into request specs, but no word on changes to this basic method of controller testing.

Recrudescence answered 24/5, 2017 at 22:38 Comment(0)
C
36

It appears that Rails 5 expects keyword arguments instead of hash arguments, which is a change from previous versions. Also, the first argument is a URL rather than an action. Try

post some_url, params: some_hash
Camail answered 24/5, 2017 at 22:47 Comment(7)
Awesome! Can you tell me how you found this? Or further documentation on "keyword arguments"? I've done a fair amount of searching, including Rails' Upgrade Notes and RSpec's GitHub Upgrading section and this still eluded me. Just some help on how to stay better up to date on things like this or other subtle Rails 5 updates.Recrudescence
Also, FWIW, post still does accept just an action, does not need a url.Recrudescence
As to how I found this, I have been answering questions about controller testing for several years, so I knew right away that this statement worked in previous versions. That narrowed it down to a change in Rails 5. A quick search led to this blog post: blog.bigbinary.com/2016/04/19/… where the switch to keyword arguments is mentioned.Camail
Great info in that article, not sure how I missed it. Thank you!Recrudescence
The first argument is absolutely not a URL, it is an action name. Why is this an accepted answer?Irenics
@AndrewKoster see github.com/rails/rails/blob/…. It takes a path or a URL. The Rails Testing Guide also uses "url" in its examples. As of Rails 5 controller tests are subclasses of ActionDispatch::IntegrationTest. Before Rails 5 they derived from ActionController::TestCase, which did take an action name.Camail
Yeah, looks like I was working from outdated documentation. We aren't even supposed to be using controller tests anymore, they've been replaced with request tests (which do take a URL as the first argument).Irenics

© 2022 - 2024 — McMap. All rights reserved.