Notes on using and testing Jbuilder

I’m going to convert these notes and tips into a blog article shortly. Here they are, in case you have any feedback.

Conversions from a Jbuilder object

  1. To a JSON string by calling target!.
  2. To a Hash by calling attributes!.
  3. To print out a Jbuilder object in the console in a nice format, say to save in a .json file:
jb = < some Jbuilder object >  
puts JSON.pretty_generate(jb.attributes!)

Testing Jbuilder

View Specs

Suppose you have a model call MyModel with a controller called MyModelsController, with a method called my_action with a view file located at /app/views/my_models/my_action.json.jbuilder that takes some member variable @some_var

/spec/views/my_models/my_action.json.jbuilder_spec.rb

require "rails_helper"

describe "benchmark jbuilder rendering" do

  it "Creates the jbuilder json" do
    @some_var = "something"
    render template: "/my_models/my_action"
   
    # Convert the JSON string, rendered, into a Hash for spec evals
    json_response = JSON.parse(rendered)

    # or use
    # api_matchers gem: https://github.com/tomas-stefano/api_matchers
    expect(rendered).to have_node("someNode")
  end
end

Request Specs

/spec/requests/my_models.rb

require "rails_helper"

describe "My Models", type: :request do
  def make_request
    get "/my_models/#{my_model.id}/my_action.json"
  end

  context "not signed in" do
    it "returns unauthorized" do
      make_request
      expect(response).to have_http_status(:unauthorized)
    end
  end

  context "signed in" do
    before { sign_in_user_as(user) }

    describe "GET /my_models/#{my_model.id}/my_action.json" do
           context "with some context" do
      
        it "returns defaults" do
          make_request
          expect(response).to have_http_status(:ok)
         
          # not providing examples of schema testing
          expect(response).to match_response_schema("my_models")
          json_response = JSON.parse(response.body)         
        end
      end
    end
end