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?
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.
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.
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.
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.
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