Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit-test a JSON controller?

This is my action:

def my_action   str = ... # get json str somehow     render :json => str end 

This is my test:

test "my test" do    post(:my_action, {'param' => "value"}       assert_response :success end 

I want to add another assertion that the emitted JSON contains some value. How can I do it in a controller unit-test, not via parsing the view result?

like image 290
Yaron Naveh Avatar asked Nov 26 '11 22:11

Yaron Naveh


People also ask

How will you unit test a controller?

Unit testing controllers. Set up unit tests of controller actions to focus on the controller's behavior. A controller unit test avoids scenarios such as filters, routing, and model binding. Tests that cover the interactions among components that collectively respond to a request are handled by integration tests.

Should you write unit tests for controllers?

Controller logic can be tested using automated integration tests, separate and distinct from unit tests for individual components. -1: A unit test for a controller could be pointless.

How do you assert JSON data?

The assertion should be that jsonData is an array and that jsonData[0] contains keys, or that all elements in jsonData contain your keys, depending on your specification. So, FWIW, this in Object, not JSON; JSON is a string. You can use jsonData.


1 Answers

Just like people commented above, this would be a functional test.

The best way would probably be making a request, parsing the JSON response body, and matching it to the expected result.

If I have companies_controller in Rspec using FactoryGirl:

describe "GET 'show'" do    before(:each) do     @company = Factory(:company)     get 'show', :format => :json, :id => @company.id   end    it "should be successful" do      response.should be_success   end    it "should return the correct company when correct id is passed" do     body = JSON.parse(response.body)     body["id"].should == @company.id   end  end 

You can test other attributes the same way. Also, I normally have invalid context where I would try to pass invalid parameters.

like image 99
Simon Bagreev Avatar answered Sep 23 '22 02:09

Simon Bagreev