A platform for community discussion. Free, open, simple.
DEV: Add RSpec matchers for JSON:API resources (#42933)
Loïc Guitaut39a8c3020734
diff --git a/lib/json_api_kit/declarations/attributes.rb b/lib/json_api_kit/declarations/attributes.rbindex 0dd5300d7ee..79b9158acfd 100644--- a/lib/json_api_kit/declarations/attributes.rb+++ b/lib/json_api_kit/declarations/attributes.rb@@ -9,6 +9,8 @@ module JsonApiKit@schema = schemaend+ def names = attributes.map(&:name)+def values_for(record) = readable(record).to_h { [it.name, it.value_for(record)] }def columns = Columns.for(attributes.map { it.column_for(schema) })diff --git a/lib/json_api_kit/resource/fields.rb b/lib/json_api_kit/resource/fields.rbindex b9794db1eb9..1ce2ff8d5dd 100644--- a/lib/json_api_kit/resource/fields.rb+++ b/lib/json_api_kit/resource/fields.rb@@ -31,6 +31,10 @@ module JsonApiKitdef has_many(name, **options) = relate(Declarations::Relationship::ToMany, name, **options)+ def attribute_names = declared_attributes.map(&:name)++ def relationships = Declarations::Relationships.new(declared_relationships)+def fields(names = nil, guardian:)Declarations::Fields.for(names,@@ -43,8 +47,6 @@ module JsonApiKitprivate- def relationships = Declarations::Relationships.new(declared_relationships)-def relate(kind, name, resource: nil, **options)self.declared_relationships =declared_relationships +diff --git a/plugins/discourse-data-explorer/spec/requests/api/queries_spec.rb b/plugins/discourse-data-explorer/spec/requests/api/queries_spec.rbindex 4132dca7935..d0fc0471264 100644--- a/plugins/discourse-data-explorer/spec/requests/api/queries_spec.rb+++ b/plugins/discourse-data-explorer/spec/requests/api/queries_spec.rb@@ -107,36 +107,6 @@ RSpec.describe "JSON:API queries", type: :request doexpect(parsed_body).to eq("data" => data, "included" => [], "links" => links)end- context "when the request sorts by name" do- let(:query_parameters) { { sort: "name" } }-- it "sends the queries in that order" do- expect(parsed_body["data"].map { it["attributes"]["name"] }).to eq(- ["Posts of the week", "Topics of a category", "Users who never posted"],- )- end- end-- context "when the request sorts by the author's username" do- fab!(:later_author) { Fabricate(:user, username: "zoe_analyst") }- fab!(:by_zoe) { Fabricate(:query, name: "Written by Zoe", user: later_author) }- fab!(:by_nobody) { Fabricate(:query, name: "Written by nobody", user: nil) }-- let(:query_parameters) { { sort: "user.username" } }-- it "sends the queries in that order, and the ones with no author last" do- expect(parsed_body["data"].map { it["attributes"]["name"] }).to eq(- [- "Posts of the week",- "Users who never posted",- "Topics of a category",- "Written by Zoe",- "Written by nobody",- ],- )- end- end-context "when the request filters by a word in the name" dolet(:query_parameters) { { filter: { search: "NEVER POSTED" } } }@@ -163,91 +133,8 @@ RSpec.describe "JSON:API queries", type: :request doendend- context "when the request limits the page size to 1" do- let(:query_parameters) { { page: { size: "1" } } }- let(:order) { DiscourseDataExplorer::QueryResource.order.first }- let(:cursor) { order.position_of(newest).to_cursor.to_s }- let(:next_page) { "#{base}/queries?#{{ page: { after: cursor, size: "1" } }.to_query}" }-- it "sends that many queries" do- expect(parsed_body["data"].map { it["attributes"]["name"] }).to eq(["Topics of a category"])- end-- it "links to the next page" do- expect(parsed_body["links"]).to eq(- "self" => {- "href" => "#{base}/queries?page%5Bsize%5D=1",- "type" => JsonApiKit::Pagination::Profile::MEDIA_TYPE,- },- "prev" => nil,- "next" => next_page,- )- end- end-- context "when the request doesn’t limit the page size" do- fab!(:filler) do- DiscourseDataExplorer::Query.insert_all(- (1..60).map do- {- name: "Filler #{it}",- sql: "SELECT 1",- created_at: Time.utc(2026, 7, 1),- updated_at: Time.utc(2026, 7, 1),- }- end,- )- end-- it "sends fifty queries" do- expect(parsed_body["data"].size).to eq(50)- end- end-- context "when the request anchors the page on one query" do- let(:query_parameters) do- { sort: "name", page: { anchor: { id: middle.id }, before_size: "1", after_size: "0" } }- end-- it "sends the page around that query" do- expect(parsed_body["data"].map { it["attributes"]["name"] }).to eq(- ["Topics of a category", "Users who never posted"],- )- end- end-context "when the request includes the author and the groups" dolet(:query_parameters) { { include: "user,groups" } }- let(:relationships) do- [newest, middle, oldest].map do |query|- {- "user" => {- "data" => {- "type" => "users",- "id" => author.id.to_s,- },- "links" => {- "self" => "#{base}/queries/#{query.id}/relationships/user",- "related" => "#{base}/queries/#{query.id}/user",- },- },- "groups" => {- "data" => [{ "type" => "groups", "id" => analysts.id.to_s }],- "links" => {- "self" => "#{base}/queries/#{query.id}/relationships/groups",- "related" => "#{base}/queries/#{query.id}/groups",- "prev" => nil,- "next" => nil,- },- },- }- end- end-- it "links every query to its author and to its groups" do- expect(parsed_body["data"].map { it["relationships"] }).to eq(relationships)- end-it "sends every related record under its own namespace" doexpect(parsed_body["included"]).to contain_exactly({@@ -308,12 +195,6 @@ RSpec.describe "JSON:API queries", type: :request do)end- context "when no query has that id" do- let(:path) { "/api/data-explorer/queries/0" }-- it { expect(response).to have_http_status(:not_found) }- end-context "when the query is hidden" dofab!(:secret) { Fabricate(:query, name: "Hidden from the listing", hidden: true) }diff --git a/plugins/discourse-data-explorer/spec/resources/discourse_data_explorer/query_resource_spec.rb b/plugins/discourse-data-explorer/spec/resources/discourse_data_explorer/query_resource_spec.rbnew file mode 100644index 00000000000..50fa12a38bb--- /dev/null+++ b/plugins/discourse-data-explorer/spec/resources/discourse_data_explorer/query_resource_spec.rb@@ -0,0 +1,24 @@+# frozen_string_literal: true++RSpec.describe DiscourseDataExplorer::QueryResource, type: :resource do+ fab!(:admin)++ it { is_expected.to declare_model(DiscourseDataExplorer::Query) }+ it { is_expected.to declare_type(:queries) }+ it { is_expected.to declare_namespace("data-explorer") }++ it { is_expected.to expose(:name, :description, :created_at, :last_run_at) }+ it { is_expected.to expose(:param_info, :is_default) }+ it { is_expected.to expose(:sql).readable_by(admin.guardian).hidden_from(Guardian.new) }++ it { is_expected.to have_one(:user) }+ it { is_expected.to have_many(:groups) }++ it { is_expected.to sort_on(:name, :last_run_at, "user.username") }+ it { is_expected.to sort_by_default(last_run_at: :desc) }++ it { is_expected.to filter_on(:search) }+ it { is_expected.to anchor_on(:id, :name, :last_run_at) }++ it { is_expected.to paginate(default: 50, max: 100) }+enddiff --git a/spec/rails_helper.rb b/spec/rails_helper.rbindex f871c9be177..f3b58e1f3b5 100644--- a/spec/rails_helper.rb+++ b/spec/rails_helper.rb@@ -93,6 +93,7 @@ RSpec.configure do |config|config.include OneboxHelpersconfig.include FastImageHelpersconfig.include ServiceMatchers+ config.include JsonApiKitMatchers, type: :resourceconfig.include I18nHelpersconfig.include TimeHelpersconfig.include AuthHelpersdiff --git a/spec/support/matchers/json_api_kit/anchor_on.rb b/spec/support/matchers/json_api_kit/anchor_on.rbnew file mode 100644index 00000000000..7eda377182a--- /dev/null+++ b/spec/support/matchers/json_api_kit/anchor_on.rb@@ -0,0 +1,43 @@+# frozen_string_literal: true++require_relative "matcher"++module JsonApiKitMatchers+ class AnchorOn < Matcher+ attr_reader :names++ def initialize(names)+ @names = names.map(&:to_s)+ end++ def satisfied?+ undeclared.empty? && unlocatable.empty?+ end++ def description+ "anchor on #{names.join(", ")}"+ end++ def failure_message+ if undeclared.any?+ return(+ "Expected #{resource} to anchor on #{undeclared.join(", ")}, " \+ "but it anchors on #{in_words(resource.anchor_names)}."+ )+ end+ "Expected #{resource} to anchor on #{unlocatable.join(", ")}, " \+ "but none of its sorts can locate a row by that name."+ end++ private++ def undeclared = @undeclared ||= names - resource.anchor_names++ def unlocatable+ @unlocatable ||=+ names.reject { resource.anchored_by?(anchor_name: it, ordering: ordering_for(it)) }+ end++ def ordering_for(name) = resource.sort_names.include?(name) ? { name => :asc } : {}+ end+enddiff --git a/spec/support/matchers/json_api_kit/declare_model.rb b/spec/support/matchers/json_api_kit/declare_model.rbnew file mode 100644index 00000000000..845410ec751--- /dev/null+++ b/spec/support/matchers/json_api_kit/declare_model.rb@@ -0,0 +1,45 @@+# frozen_string_literal: true++require_relative "matcher"++module JsonApiKitMatchers+ class DeclareModel < Matcher+ attr_reader :model++ def initialize(model)+ @model = model+ end++ def satisfied?+ resource_model == model && model.table_exists?+ end++ def description+ "declare the model #{model}"+ end++ def failure_message+ return missing_model_message unless resource_model+ if resource_model != model+ return(+ "Expected #{resource} to declare the model #{model}, but it declares #{resource_model}."+ )+ end+ "Expected #{resource} to declare the model #{model}, " \+ "but the table #{model.table_name} does not exist."+ end++ private++ def resource_model+ @resource_model ||= resource.model+ rescue JsonApiKit::Resource::MissingDeclaration => error+ @missing = error.message+ nil+ end++ def missing_model_message+ "Expected #{resource} to declare the model #{model}, but it has no model: #{@missing}"+ end+ end+enddiff --git a/spec/support/matchers/json_api_kit/declare_namespace.rb b/spec/support/matchers/json_api_kit/declare_namespace.rbnew file mode 100644index 00000000000..a96f72a8c05--- /dev/null+++ b/spec/support/matchers/json_api_kit/declare_namespace.rb@@ -0,0 +1,26 @@+# frozen_string_literal: true++require_relative "matcher"++module JsonApiKitMatchers+ class DeclareNamespace < Matcher+ attr_reader :namespace++ def initialize(namespace)+ @namespace = namespace.to_s+ end++ def satisfied?+ resource.namespace == namespace+ end++ def description+ "declare the namespace #{namespace.inspect}"+ end++ def failure_message+ "Expected #{resource} to declare the namespace #{namespace.inspect}, " \+ "but it declares #{resource.namespace&.inspect || "none"}."+ end+ end+enddiff --git a/spec/support/matchers/json_api_kit/declare_type.rb b/spec/support/matchers/json_api_kit/declare_type.rbnew file mode 100644index 00000000000..a8b8e7fe986--- /dev/null+++ b/spec/support/matchers/json_api_kit/declare_type.rb@@ -0,0 +1,26 @@+# frozen_string_literal: true++require_relative "matcher"++module JsonApiKitMatchers+ class DeclareType < Matcher+ attr_reader :type++ def initialize(type)+ @type = type.to_s+ end++ def satisfied?+ resource.type == type+ end++ def description+ "declare the type #{type.inspect}"+ end++ def failure_message+ "Expected #{resource} to declare the type #{type.inspect}, " \+ "but it declares #{resource.type.inspect}."+ end+ end+enddiff --git a/spec/support/matchers/json_api_kit/expose.rb b/spec/support/matchers/json_api_kit/expose.rbnew file mode 100644index 00000000000..2d82e57c243--- /dev/null+++ b/spec/support/matchers/json_api_kit/expose.rb@@ -0,0 +1,88 @@+# frozen_string_literal: true++require_relative "matcher"++module JsonApiKitMatchers+ class Expose < Matcher+ attr_reader :names++ def initialize(names)+ @names = names.map(&:to_s)+ end++ def readable_by(guardian, record: nil)+ @reader = guardian+ @reader_record = record+ self+ end++ def hidden_from(guardian, record: nil)+ @stranger = guardian+ @stranger_record = record+ self+ end++ def satisfied?+ undeclared.empty? && hidden.empty? && shown.empty? && broken_attribute.nil?+ end++ def description+ ["expose #{names.join(", ")}", *readable_clause, *hidden_clause].join(", ")+ end++ def failure_message+ return undeclared_message if undeclared.any?+ return broken_attribute_message if broken_attribute+ return hidden_message if hidden.any?+ shown_message+ end++ private++ attr_reader :reader, :stranger, :broken_attribute++ def undeclared = @undeclared ||= names - resource.attribute_names++ def hidden = @hidden ||= reader ? names - names_for_reader : []++ def shown = @shown ||= stranger ? names & names_for_stranger : []++ def names_for_reader = readable(reader, @reader_record)++ def names_for_stranger = readable(stranger, @stranger_record)++ def readable(guardian, record)+ attributes = resource.fields(guardian:).attributes+ return attributes.names unless record+ attributes.values_for(record).keys+ rescue NoMethodError => error+ @broken_attribute = error.name+ []+ end++ def broken_attribute_message+ "Expected #{resource} to expose #{names.join(", ")}, but the attribute " \+ "#{broken_attribute} cannot be read from a #{resource.model}."+ end++ def readable_clause = reader ? ["readable by #{name_of(reader)}"] : []++ def hidden_clause = stranger ? ["hidden from #{name_of(stranger)}"] : []++ def name_of(guardian) = guardian.user&.username || "anonymous"++ def undeclared_message+ "Expected #{resource} to expose #{undeclared.join(", ")}, " \+ "but it exposes #{in_words(resource.attribute_names)}."+ end++ def hidden_message+ "Expected #{resource} to expose #{hidden.join(", ")} to #{name_of(reader)}, but it is hidden."+ end++ def shown_message+ "Expected #{resource} to hide #{shown.join(", ")} from #{name_of(stranger)}, " \+ "but it is readable."+ end+ end+enddiff --git a/spec/support/matchers/json_api_kit/filter_on.rb b/spec/support/matchers/json_api_kit/filter_on.rbnew file mode 100644index 00000000000..835f34ee786--- /dev/null+++ b/spec/support/matchers/json_api_kit/filter_on.rb@@ -0,0 +1,50 @@+# frozen_string_literal: true++require_relative "matcher"++module JsonApiKitMatchers+ class FilterOn < Matcher+ PROBE = "a value no row holds"++ attr_reader :names++ def initialize(names)+ @names = names.map(&:to_s)+ end++ def satisfied?+ return false if undeclared.any?+ @failure = filter_failure+ @failure.nil?+ end++ def description+ "filter on #{names.join(", ")}"+ end++ def failure_message+ if undeclared.any?+ return(+ "Expected #{resource} to filter on #{undeclared.join(", ")}, " \+ "but it filters on #{in_words(resource.filter_names)}."+ )+ end+ name, error = @failure+ "Expected #{resource} to filter on #{name}, but filtering by it raised #{error.class}: " \+ "#{error.message.lines.first.strip}"+ end++ private++ def undeclared = @undeclared ||= names - resource.filter_names++ def filter_failure+ names.each do |name|+ resource.all({ filter: { name => PROBE } }, guardian: Guardian.new).records+ rescue StandardError => error+ return name, error+ end+ nil+ end+ end+enddiff --git a/spec/support/matchers/json_api_kit/have_relationship.rb b/spec/support/matchers/json_api_kit/have_relationship.rbnew file mode 100644index 00000000000..22ab87c8f6b--- /dev/null+++ b/spec/support/matchers/json_api_kit/have_relationship.rb@@ -0,0 +1,67 @@+# frozen_string_literal: true++require_relative "matcher"++module JsonApiKitMatchers+ class HaveRelationship < Matcher+ KINDS = {+ one: JsonApiKit::Declarations::Relationship::ToOne,+ many: JsonApiKit::Declarations::Relationship::ToMany,+ }.freeze++ attr_reader :name, :kind++ def initialize(name, kind)+ @name = name.to_s+ @kind = kind+ end++ def satisfied?+ relationship && right_kind? && association_table && tables_agree?+ end++ def description+ "have #{kind} #{name}"+ end++ def failure_message+ unless relationship+ return "Expected #{resource} to #{description}, but it declares #{declared_names}."+ end+ return "Expected #{resource} to #{description}, but it has #{other_kind}." unless right_kind?+ return missing_association_message unless association_table+ table_mismatch_message+ end++ private++ def relationship = @relationship ||= resource.relationships.pick([name]).first++ def right_kind? = relationship.instance_of?(KINDS.fetch(kind))++ def other_kind = kind == :one ? "many" : "one"++ def declared_names = in_words(resource.relationships.names)++ def association_table+ @association_table ||= resource.schema.table_of(name.to_sym)+ rescue JsonApiKit::Schema::MissingAssociation => error+ @missing = error.message+ nil+ end++ def related_table = relationship.resource.model.table_name++ def tables_agree? = association_table == related_table++ def missing_association_message+ "Expected #{resource} to #{description}, but #{resource.model} has no association " \+ "named #{name}."+ end++ def table_mismatch_message+ "Expected #{resource} to #{description}, but the association reads #{association_table} " \+ "and #{relationship.resource} reads #{related_table}."+ end+ end+enddiff --git a/spec/support/matchers/json_api_kit/matcher.rb b/spec/support/matchers/json_api_kit/matcher.rbnew file mode 100644index 00000000000..9ec8237240b--- /dev/null+++ b/spec/support/matchers/json_api_kit/matcher.rb@@ -0,0 +1,22 @@+# frozen_string_literal: true++module JsonApiKitMatchers+ class Matcher+ attr_reader :resource++ def matches?(resource)+ @resource = resource+ satisfied?+ end++ def failure_message_when_negated+ "Expected #{resource} not to #{description}."+ end++ private++ def in_words(names)+ names.join(", ").presence || "none"+ end+ end+enddiff --git a/spec/support/matchers/json_api_kit/paginate.rb b/spec/support/matchers/json_api_kit/paginate.rbnew file mode 100644index 00000000000..3bea803e89d--- /dev/null+++ b/spec/support/matchers/json_api_kit/paginate.rb@@ -0,0 +1,27 @@+# frozen_string_literal: true++require_relative "matcher"++module JsonApiKitMatchers+ class Paginate < Matcher+ attr_reader :default, :max++ def initialize(default:, max:)+ @default = default+ @max = max+ end++ def satisfied?+ resource.page_size == default && resource.max_page_size == max+ end++ def description+ "paginate #{default} rows at a time, #{max} at most"+ end++ def failure_message+ "Expected #{resource} to #{description}, but it paginates #{resource.page_size} " \+ "at a time, #{resource.max_page_size} at most."+ end+ end+enddiff --git a/spec/support/matchers/json_api_kit/sort_by_default.rb b/spec/support/matchers/json_api_kit/sort_by_default.rbnew file mode 100644index 00000000000..fd7e44c5d7f--- /dev/null+++ b/spec/support/matchers/json_api_kit/sort_by_default.rb@@ -0,0 +1,52 @@+# frozen_string_literal: true++require_relative "matcher"++module JsonApiKitMatchers+ class SortByDefault < Matcher+ attr_reader :ordering++ def initialize(ordering)+ @ordering = ordering.to_h { |name, direction| [name.to_s, direction.to_sym] }+ end++ def satisfied?+ leading_keys == ordering.to_a && runs?+ end++ def description+ "sort by default on #{ordering.map { |name, direction| "#{name} #{direction}" }.join(", ")}"+ end++ def failure_message+ if leading_keys != ordering.to_a+ return "Expected #{resource} to #{description}, but it sorts on #{spell(leading_keys)}."+ end+ "Expected #{resource} to #{description}, but reading it raised #{@error.class}: " \+ "#{@error.message.lines.first.strip}"+ end++ private++ def leading_keys+ @leading_keys ||=+ resource+ .order+ .first+ .keyset+ .keys+ .first(ordering.size)+ .map { [it.name.to_s, it.direction.to_sym] }+ end++ def spell(pairs) = in_words(pairs.map { |name, direction| "#{name} #{direction}" })++ def runs?+ resource.all({}, guardian: Guardian.new).records+ true+ rescue StandardError => error+ @error = error+ false+ end+ end+enddiff --git a/spec/support/matchers/json_api_kit/sort_on.rb b/spec/support/matchers/json_api_kit/sort_on.rbnew file mode 100644index 00000000000..88b29da74f1--- /dev/null+++ b/spec/support/matchers/json_api_kit/sort_on.rb@@ -0,0 +1,53 @@+# frozen_string_literal: true++require_relative "matcher"++module JsonApiKitMatchers+ class SortOn < Matcher+ DIRECTIONS = { asc: "ascending", desc: "descending" }.freeze++ attr_reader :names++ def initialize(names)+ @names = names.map(&:to_s)+ end++ def satisfied?+ return false if undeclared.any?+ @failure = sort_failure+ @failure.nil?+ end++ def description+ "sort on #{names.join(", ")}"+ end++ def failure_message+ return undeclared_message if undeclared.any?+ name, direction, error = @failure+ "Expected #{resource} to sort on #{name}, but reading it #{DIRECTIONS.fetch(direction)} " \+ "raised " \+ "#{error.class}: #{error.message.lines.first.strip}"+ end++ private++ def undeclared = @undeclared ||= names - resource.sort_names++ def undeclared_message+ "Expected #{resource} to sort on #{undeclared.join(", ")}, " \+ "but it sorts on #{in_words(resource.sort_names)}."+ end++ def sort_failure+ names+ .product(DIRECTIONS.keys)+ .each do |name, direction|+ resource.all({ sort: { name => direction } }, guardian: Guardian.new).records+ rescue StandardError => error+ return name, direction, error+ end+ nil+ end+ end+enddiff --git a/spec/support/matchers/json_api_kit_matchers.rb b/spec/support/matchers/json_api_kit_matchers.rbnew file mode 100644index 00000000000..4005dc86717--- /dev/null+++ b/spec/support/matchers/json_api_kit_matchers.rb@@ -0,0 +1,64 @@+# frozen_string_literal: true++require_relative "json_api_kit/anchor_on"+require_relative "json_api_kit/declare_model"+require_relative "json_api_kit/declare_namespace"+require_relative "json_api_kit/declare_type"+require_relative "json_api_kit/expose"+require_relative "json_api_kit/filter_on"+require_relative "json_api_kit/have_relationship"+require_relative "json_api_kit/paginate"+require_relative "json_api_kit/sort_by_default"+require_relative "json_api_kit/sort_on"++RSpec.shared_context "with a JSON:API resource" do+ subject(:resource) { described_class }+end++RSpec.configure { |config| config.include_context "with a JSON:API resource", type: :resource }++module JsonApiKitMatchers+ def declare_model(model)+ DeclareModel.new(model)+ end++ def declare_type(type)+ DeclareType.new(type)+ end++ def declare_namespace(namespace)+ DeclareNamespace.new(namespace)+ end++ def expose(*names)+ Expose.new(names)+ end++ def have_one(name)+ HaveRelationship.new(name, :one)+ end++ def have_many(name)+ HaveRelationship.new(name, :many)+ end++ def sort_on(*names)+ SortOn.new(names)+ end++ def sort_by_default(ordering)+ SortByDefault.new(ordering)+ end++ def filter_on(*names)+ FilterOn.new(names)+ end++ def anchor_on(*names)+ AnchorOn.new(names)+ end++ def paginate(default:, max:)+ Paginate.new(default:, max:)+ end+end