Skip to content

Instantly share code, notes, and snippets.

@ndbroadbent
Last active May 15, 2020 13:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ndbroadbent/a01ccaa20e696e1c5fa20d89b8593756 to your computer and use it in GitHub Desktop.
Save ndbroadbent/a01ccaa20e696e1c5fa20d89b8593756 to your computer and use it in GitHub Desktop.
RSpec test to ensure that the Oj gem is working in a Rails application
# frozen_string_literal: true
require 'rails_helper'
# This test makes sure that Oj is used to parse and generate all JSON.
# Your application needs to call: Oj.optimize_rails
# See: https://github.com/ohler55/oj/blob/develop/pages/Rails.md#notes
RSpec.describe 'Oj gem' do
it 'uses OJ to parse and generate JSON' do
traced_calls = []
tracer = TracePoint.new(:c_call) do |tp|
traced_calls << [tp.defined_class, tp.method_id]
end
tracer.enable { 123.to_json }
expect(traced_calls).to include [Oj::Rails::Encoder, :encode]
traced_calls = []
serializer = YourSerializerClass.new(build(:your_factory))
tracer.enable { serializer.to_json }
expect(traced_calls).to include [Oj::Rails::Encoder, :encode]
traced_calls = []
tracer.enable { JSON.parse('{"foo": 123}') }
# If Oj is not loaded, this will be: "[[Class, :new], [JSON::Ext::Parser, :initialize], ...
expect(traced_calls.to_s).to eq '[[#<Class:JSON>, :parse]]'
expect do
JSON.parse('{"a":x123}')
end.to raise_error(
JSON::ParserError,
"unexpected character (a) at line 1, column 6 [parse.c:705] in '{\"a\":x123}"
)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment