swsnu / wecfall2014

0 stars 0 forks source link

How to test JSON responses with rspec #7

Open HaritzPuerto opened 9 years ago

HaritzPuerto commented 9 years ago

Hello again.

I've written the responses in json and now I want to test them but I don't know how. I only found this: http://stackoverflow.com/questions/5159882/how-to-check-for-a-json-response-using-rspec but I still don't know how to do it. I've made a test in spec/controllers with the following code: require 'spec_helper'

describe User do

before { @user = User.new(username: "Haritz", password: "123456789") }

subject { @user }

describe "with correct input" do
    it "should respond json" do
            post 'signup.json'
            expect(json["user_name"]).to eq('Haritz')
            expect(json["login_count"]).to eq('1234567890')
        end
end

end

but when I try it I obtain the following error: Failure/Error: Unable to find matching line from backtrace NoMethodError: undefined method `request=' for #User:0x0000000351aab0

How can I test it?

Thank you very much!

nosoyilse commented 9 years ago

I don't know how to use a tool to test the responses but I think that if you use cucumber you can test the output on the screen and with that validate the current json response. Because the json response can output the error on the screen like 404 error, and then with cucumber you test to see the error number you got.

Here is a tutorial link: https://github.com/cucumber/cucumber/wiki/Tutorials-and-Related-Blog-Posts

bgchun commented 9 years ago

@johnyangk @taegeonum Maybe you guys can check out @HaritzUMA's code to help him during the class.

johnyangk commented 9 years ago

@bgchun Okay, we will help @HaritzUMA in the next class(Wednesday).

HaritzPuerto commented 9 years ago

Thank you!!

HaritzPuerto commented 9 years ago

The problem is solved! Thank you @johnyangk @taegeonum . I had to do this tests in spec/controllers and the first Describe must have the name of the controller I am using. Then, a code like this should work:

it "should respond json" do
      post 'create', {:username => 'ppppp', :password => '1234567890', :format => :json}
      json = JSON.parse(response.body)
      expect(json["user_name"]).to eq('ppppp')
      expect(json["login_count"]).to eq(1)
end

Hope it helps!