Patrick Johnson
Patrick Johnson

Reputation: 31

RSpec Controller test converting hash into String

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

Upvotes: 2

Views: 1038

Answers (2)

Patrick Johnson
Patrick Johnson

Reputation: 31

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

Upvotes: 0

Del
Del

Reputation: 407

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' }

Upvotes: 2

Related Questions