2

I have a controller spec for my application, which tests the create method on a controller. The create action actually works fine, but the spec is failing. It seems that it is auto converting the the hash POST param into a string.

let(:coupon) { attributes_for(:coupon) }

describe 'POST #create' do
  it 'should create a new coupon from params' do
    expect {
      post :create, :coupon => coupon
    }.to change(Coupon, :count).by(1)
  end
end

Now, If I do puts coupon it is generating a valid hash of data, and the type is hash. For some reason the controller is receiving a string for params[:coupon]. Only in rspec testing does this happen, when I test in the browse with a POST form it works perfectly fine.

Rspec throws the following message:

NoMethodError:
   undefined method `permit' for #<String:0x00000005062700>
   Did you mean?  print

and if I do puts params[:coupon].class in the controller in rspec it gives me String. Why might it be converting my hash into a string for the POST request, and how can I prevent this ?

I am using Rails 5.0.0 and rspec 3.5.1

2 Answers 2

2

This exact same behavior showed up for me recently when testing a JSON API endpoint. Originally I had this as my subject:

subject { put :my_endpoint, **input_args }

and an integer value in input_args was getting translated into a string. The fix was to add format: 'json' as an additional keyword argument to put:

subject { put :my_endpoint, **input_args, format: 'json' }
Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunatly this did not fix, and I have already been trying to test it using various JSON functions. My entire coupon hash is being converted into string. In the controller, when using params.require(:coupon), it is getting a string rather than a hash so It cannot access any of the hash's values.
0

It seems that it was an issue with the gem open_taobao somehow transforming my post requests in tests.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.