4

I'm trying to pass an array in the query string of an rspec test but it's giving me an error. I will be sending query strings like "products[]=desk,chair" and expect the controller to be able to handle it.

Here's the error:

Failure/Error: get :index, { :format => :json, :products => [product_1, product_2]}, { "Accept" => "application/json" }
NoMethodError:
       undefined method `each' for "[\"desk\", \"chair\"]":String

Here's my test method:

product_1 = "desk"
product_2 = "chair"
get :index, { :format => :json, :products => [product_1, product_2]}, { "Accept" => "application/json" }

Heres my controller:

products.each do |product|
    puts "product: #{product}"
end

def products
    params[:products].to_s
end

Any ideas?

Note: this is running Rails 3.2.12

2
  • any ideas on how to fix this problem? I will be sending query strings like "products[]=desk,chair" and expect the controller to be able to handle it Commented Dec 14, 2015 at 21:41
  • 1
    Well, you are converting your params into a string so you have a string. You also should be sending products[]=desk&products[]=chair if you want an array. Commented Dec 14, 2015 at 21:43

1 Answer 1

4

You are defining products as params[:products].to_s that makes it an string, no matter what you send. So when you do products.each in the index method it fails.

Do the each on params[:products] instead:

def index
  params[:products].each do |product|
    puts "product: #{product}"
  end
end

I'm sure that puts, is just troubleshooting code, but you shouldn't use it on your controller.

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

1 Comment

awesome! thank you! can't believe I missed that one haha

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.