Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extract custom parser tests to a separate feature spec file #234

Merged
merged 1 commit into from
May 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions spec/features/custom_parser_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# 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