Skip to content

Commit

Permalink
Extract custom parser tests to a separate feature spec file
Browse files Browse the repository at this point in the history
  • Loading branch information
mvz committed May 12, 2024
1 parent a34075a commit f2113a9
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 33 deletions.
53 changes: 53 additions & 0 deletions spec/features/custom_parser_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# frozen_string_literal: true

require "spec_helper"

class ParserTest
include HappyMapper

class Coerce
def self.number_list(val)
val.to_s.split(",").map { _1.strip.to_i }
end
end

tag "parsertest"
attribute :numbers, Coerce, parser: :number_list
element :strings, self, parser: :string_list
element :bool, String, parser: ->(val) { val.to_s == "1" }

def self.string_list(val)
val.to_s.split(",").map(&:strip)
end
end

RSpec.describe "specifying a custom parser for attributes and elements" do
let(:xml) do
<<~XML
<parsertest numbers="1,2,3">
<strings>a, b, c</strings>
<bool>0</bool>
</parsertest>
XML
end

it "parses with a singleton method on the type class" do
parsed = ParserTest.parse xml

expect(parsed.numbers).to eq [1, 2, 3]
end


it "parses with a singleton method on the model class" do
parsed = ParserTest.parse xml

expect(parsed.strings).to eq %w(a b c)
end


it "parses with a proc specified in the element definition" do
parsed = ParserTest.parse xml

expect(parsed.bool).to be false
end
end
4 changes: 0 additions & 4 deletions spec/fixtures/custom_parsers.xml

This file was deleted.

29 changes: 0 additions & 29 deletions spec/happymapper_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -560,25 +560,6 @@ class Thing
end
end

class ParserTest
include HappyMapper

class Coerce
def self.number_list(val)
val.to_s.split(",").map { _1.strip.to_i }
end
end

tag "parsertest"
attribute :numbers, Coerce, parser: :number_list
element :strings, self, parser: :string_list
element :bool, String, parser: ->(val) { val.to_s == "1" }

def self.string_list(val)
val.to_s.split(",").map(&:strip)
end
end

describe HappyMapper do
describe "being included into another class" do
let(:klass) do
Expand Down Expand Up @@ -1235,14 +1216,4 @@ def self.string_list(val)
end
end
end

it "parses with custom parser" do
parsed = ParserTest.parse fixture_file("custom_parsers.xml")

aggregate_failures do
expect(parsed.numbers).to eq [1, 2, 3]
expect(parsed.strings).to eq %w(a b c)
expect(parsed.bool).to be false
end
end
end

0 comments on commit f2113a9

Please sign in to comment.