0

I am writing a test for a method that is doing an SQL query. For this project they need the response to be JSON. My test is to see that the query returns the expected number of responses. I've run into a road block since my object is JSON instead of an array. How do I convert the JSON to an ARRAY?

  test "works" do
    report = get :method
    assert_equal 1, report.count
  end

NoMethodError: undefined method `count'...

I've tried adding array_report = ActiveSupport::JSON.decode(report) but I get the following error message.

TypeError: no implicit conversion of ActionController::TestResponse into String

How can I parse the JSON correctly?

EDIT

  def method
    sql = "SELECT MIN(departure_date), ch_invoice.invoice_id
    FROM ch_invoice
    INNER JOIN ch_trip
    ON ch_invoice.invoice_id = ch_trip.invoice_id
    WHERE departure_date < SYSDATE
    AND service_rendered = 0
    AND paid = 1
    Group By ch_invoice.invoice_id"

    report = ActiveRecord::Base.connection.exec_query(sql)
    render json: report
  end

EDIT 2

Sample JSON.parse code. This is what the query giving me.

{"min(departure_date)"=>"2015-03-01T00:00:00.000Z", "invoice_id"=>"123catfood"}
{"min(departure_date)"=>"2015-01-01T00:00:00.000Z", "invoice_id"=>"123dogfood"}
CheeseFry
  • 1,299
  • 1
  • 21
  • 38

1 Answers1

1

JSON.parse <string> is probably what you need here. It could look something like this:

test "works" do
  get :method

  result = JSON.parse(response.body)

  assert_equal 1, result.count
end

Check out "How to unit-test a JSON controller?" and the ActiveSupport JSON documention.

Community
  • 1
  • 1
matt721
  • 34
  • 5
  • This is giving me a count for each cell in the query. So "Bugs" "Bunny" is 2, when I'd like it to be one ROW of data. Thoughts on how to fix this? – CheeseFry Apr 06 '16 at 21:38
  • Could you post an example JSON.parse(response.body) is so that I can see what we're working with? – matt721 Apr 06 '16 at 21:44
  • Your code is right. I just realized I'm hitting the wrong thing. I was expecting to only hit my sample data from my factory but I'm actually punching through to my db and pulling data. That's No Bueno. – CheeseFry Apr 06 '16 at 21:59
  • Ah okay. Cool. :-) – matt721 Apr 06 '16 at 22:09