使用RSpec 2.6 / Rails 3.1 / Postgres:
我正在编写一个支持模块(在我的lib /)中,AR模型可以包含.我想为此模块编写规范.它需要包含在AR :: Base模型中,因为它在包含时加载了关联,并且依赖于某些AR方法,但是在为此模块编写rspec时,我不想使用我现有的模型.
我只想创建一个任意的AR模型,但显然它不会在数据库中与表相关联,而AR正在死亡.这里很好,我想做什么:
class SomeRandomModel < ActiveRecord::Base include MyModule # simulate DB attributes that MyModule would be using attr_accessor :foo,:bar,:baz end describe SomeRandomModel do it '#some_method_in_my_module' do srm = SomeRandomModel.new(:foo => 1) srm.some_method_in_my_module.should eq(something) end end
当然,我在postgres中有一些关于不存在的关系的错误.
谢谢你的帮助!
解决方法
有一种替代方法来解决这个问题,使用rpsecs shared_examples_for,我在代码片段中提到了一些技巧,但是有关更多信息,请参阅这个
relishapp-rspec-guide.
有了这个,你可以在包含它的任何类中测试你的模块.所以你真的在测试你在应用程序中使用什么.
我们来看一个例子:
# Lets assume a Movable module module Movable def self.movable_class? true end def has_feets? true end end # Include Movable into Person and Animal class Person < ActiveRecord::Base include Movable end class Animal < ActiveRecord::Base include Movable end
现在可以为我们的模块创建规范:movable_spec.rb
shared_examples_for Movable do context 'with an instance' do before(:each) do # described_class points on the class,if you need an instance of it: @obj = described_class.new # or you can use a parameter see below Animal test @obj = obj if obj.present? end it 'should have feets' do @obj.has_feets?.should be_true end end context 'class methods' do it 'should be a movable class' do described_class.movable_class?.should be_true end end end # Now list every model in your app to test them properly describe Person do it_behaves_like Movable end describe Animal do it_behaves_like Movable do let(:obj) { Animal.new({ :name => 'capybara' }) } end end