5

I am writing a spec for the create method of a controller :

describe "POST create" do

    it "should create an adtag with valid params" do
      campaign = Campaign.make

      campaign_attributes = Hash.new
      campaign_attributes[:adtag_attributes] = Hash.new
      campaign_attributes[:adtag_attributes][:code] = "<h1>Sample code</h1>"

      post 'create', { :id => campaign.id, :campaign => campaign_attributes }
    end

end

But when I run it, I get the error "Symbol as array index" in the controller, when it tries to process this code :

params[:campaign][:adtag_attributes].each_with_index do |attributes,index|
  # some code
end

Any idea ? Thanks

EDIT 1:

I haven't written the controller, but it works with manual testing. The view that calls my controller has this code:

fields_for 'campaign[adtag_attributes][]', adtag do |adtag_form|

Maybe my spec isn't good ?

EDIT 2:

Problem resolved thanks to Rishav's answer. I didn't understand that in the view, campaign[adtag_attributes][] means that campaign[adtag_attributes] is an Array.

So I just replaced

campaign_attributes = Hash.new
campaign_attributes[:adtag_attributes] = Hash.new
campaign_attributes[:adtag_attributes][:code] = "<h1>Sample code</h1>"

by

campaign_attributes = Hash.new
campaign_attributes[:adtag_attributes] = Array.new
campaign_attributes[:adtag_attributes] << { :code => "<h1>Sample code</h1>" }

and it worked out.

1 Answer 1

5

params[:campaign][:adtag_attributes] is a hash not an array, so when it runs "each_with_index" method on the hash it sees ":code" symbol as the index and throws that error.

You can just do this

 params[:campaign][:adtag_attributes].each do |key,value|
    #some code
 end

just change to following in the test

params[:campaign][:adtag_attributes] = []
params[:campaign][:adtag_attributes] << somedata

hopefully this works

Sign up to request clarification or add additional context in comments.

1 Comment

I haven't written the controller, but it works with manual testing. See my post edit for more details.

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.