Skip to content

Commit

Permalink
Add testing the class of a serializer instance
Browse files Browse the repository at this point in the history
  • Loading branch information
Hakon authored and Gabe Berke-Williams committed Mar 16, 2012
1 parent f1a3dca commit d9906d8
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 14 deletions.
35 changes: 21 additions & 14 deletions lib/shoulda/matchers/active_record/serialize_matcher.rb
Expand Up @@ -24,6 +24,11 @@ def as(type)
@type = type
self
end

def as_instance_of(type)
@instance_type = type
self
end

def matches?(subject)
@subject = subject
Expand Down Expand Up @@ -58,26 +63,28 @@ def serialization_valid?
false
end
end

def type_valid?
def class_valid?
if @type
klass = model_class.serialized_attributes[@name]

if klass == @type
true
else
if klass.object_class == @type
true
else
@missing = ":#{@name} should be a type of #{@type}"
false
end
end
model_class.serialized_attributes[@name] == @type
else
true
end
end

def instance_class_valid?
if @instance_type
klass = model_class.serialized_attributes[@name].class
klass == @instance_type
else
true
end
end

def type_valid?
class_valid? && instance_class_valid?
end

def expectation
expectation = "#{model_class.name} to serialize the attribute called :#{@name}"
expectation += " with a type of #{@type}" if @type
Expand Down
25 changes: 25 additions & 0 deletions spec/shoulda/active_record/serialize_matcher_spec.rb
Expand Up @@ -23,6 +23,10 @@
it "should be serialized" do
model.should serialize(:attr).as(Hash)
end

it "should not match when using as_instance_of" do
model.should_not serialize(:attr).as_instance_of(Hash)
end
end

context "an attribute that should be serialized with a type of Array" do
Expand Down Expand Up @@ -52,5 +56,26 @@
matcher.matches?(model).should == false
matcher.failure_message.should_not be_nil
end

context "a serializer that is an instance of a class" do
before do
define_constant(:ExampleSerializer, Object) do
def load(*); end
def dump(*); end
end
define_model :example, :attr => :string do
serialize :attr, ExampleSerializer.new
end
@model = Example.new
end

it "should match when using as_instance_of" do
@model.should serialize(:attr).as_instance_of(ExampleSerializer)
end

it "should not match when using as" do
@model.should_not serialize(:attr).as(ExampleSerializer)
end
end
end
end

0 comments on commit d9906d8

Please sign in to comment.