2012-02-23 72 views
3

我想使用rspec来测试序列化哈希的有效性,但我真的不知道如何去做。有没有一种方法来验证散列具有特定的键和值?Rails ActiveRecord序列化数据Rspec测试

foo.rb

class Foo < ActiveRecord::Base 
    attr_accessor :bar 
    serialize :bar 

end 

foo_spec.rb:

require 'spec_helper' 

describe Route do 
    before { @foo = Foo.new(bar: { a: 1, b: 2, c: 3 }) } 

    subject { @foo } 

    it { should #????? } 
end 

回答

3

要确保序列化实际上是工作,你会想create记录,不只是new初始化(即将其保存到数据库中,然后将其存储为YAML)。然后你可以读回它(使用reload来确保它实际上是检索序列化的数据库版本):

it "deserializes the hash" do 
    @foo.reload.bar.should eq({a: 1, b:2, c: 3}) 
end 
+0

谢谢;我在前面的块中添加了一个'@ foo.save',并且能够在我的测试中重新加载'@ foo'实例。似乎现在正在工作。 – rringler 2012-02-24 01:38:30