Last active
May 17, 2019 15:09
-
-
Save ilyazub/92438c70818f75322565 to your computer and use it in GitHub Desktop.
RSpec matcher for grape-entity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Alternative: https://github.com/agileanimal/grape-entity-matchers | |
RSpec::Matchers.define :represent do |expected| | |
match do |actual| | |
exposes? && aliases? && has_presenter? && has_runtime_exposure? | |
end | |
chain :as do |as_alias| | |
@as_alias = as_alias | |
end | |
chain :using do |entity| | |
@entity = entity | |
end | |
chain :exposes_at_runtime do |object, exposure| | |
@transformation_object, @transformation_exposure = object, exposure | |
end | |
private | |
def exposes? | |
actual.exposures.key?(expected) | |
end | |
def aliases? | |
actual.exposures[expected][:as] == @as_alias | |
end | |
def has_presenter? | |
actual.exposures[expected][:using] == @entity | |
end | |
def has_runtime_exposure? | |
if @transformation_object && @transformation_exposure | |
actual.exposures[expected][:proc].call(@transformation_object) == @transformation_exposure | |
else | |
true | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Entities | |
class Value | |
expose :code | |
expose :desc, as: :description | |
end | |
class Parameter | |
expose :id do |parameter| | |
parameter.id.to_s | |
end | |
expose :variable | |
expose :desc, as: :description | |
expose :values, using: Value | |
end | |
# Specs | |
RSpec.describe Value do | |
subject { Value } | |
it { is_expected.to represent(:code) } | |
it { is_expected.to represent(:desc).as(:description) } | |
end | |
RSpec.describe Parameter do | |
subject { Parameter } | |
let(:parameter) { OpenStruct.new(id: UUIDTools::UUID.random_create) } | |
# One-liner syntax (https://relishapp.com/rspec/rspec-core/docs/subject/one-liner-syntax) | |
it { is_expected.to represent(:id).exposes_at_runtime(parameter, parameter.id.to_s) } | |
it { is_expected.to represent(:variable) } | |
it { is_expected.to represent(:desc).as(:description) } | |
it 'expected to represent values' do | |
expect(subject).to represent(:values).using(OnOff::API::Entities::Value) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment