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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With