Created
February 24, 2011 10:05
-
-
Save txus/842004 to your computer and use it in GitHub Desktop.
RSpec matcher for serialized ActiveRecord columns
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
# RSpec matcher to spec serialized ActiveRecord attributes. | |
# | |
# Usage: | |
# | |
# describe Post do | |
# it { should serialize(:data) } # serialize :data | |
# it { should serialize(:registers).as(Array) } # serialize :registers, Array | |
# it { should serialize(:options).as(Hash) } # serialize :options, Hash | |
# end | |
RSpec::Matchers.define :serialize do |attribute| | |
chain(:as) { |type| @as = type } | |
match do |model| | |
@model = model.is_a?(Class) ? model : model.class | |
@model.serialized_attributes.keys.should include(attribute.to_s) | |
@model.serialized_attributes[attribute.to_s].should == @as if @as | |
end | |
description do | |
"serialize :#{attribute}" << (@as ? " as a #{@as}" : "") | |
end | |
failure_message_for_should do |text| | |
"expected #{@model} to serialize :#{attribute}" << (@as ? " as a #{@as}" : "") | |
end | |
failure_message_for_should_not do |text| | |
"expected #{@model} not to serialize :#{attribute}" << (@as ? " as a #{@as}" : "") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for sharing! I was looking for a way to test my serialized model attributes :)
FYI, rspec 3.0+ will throw a deprecation warning for the failure matchers and should be updated to "failure_message" and "failure_message_when_negated" in place of "failure_message_for_should" and "failure_message_for_should_not", respectively.
Here is the documentation for those matchers: http://rubydoc.info/gems/rspec-expectations/RSpec/Matchers/DSL/Macros/Deprecated