加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何RSpec一个共享的ActiveRecord模块没有关联

发布时间:2020-12-16 19:51:43 所属栏目:百科 来源:网络整理
导读:使用RSpec 2.6 / Rails 3.1 / Postgres: 我正在编写一个支持模块(在我的lib /)中,AR模型可以包含.我想为此模块编写规范.它需要包含在AR :: Base模型中,因为它在包含时加载了关联,并且依赖于某些AR方法,但是在为此模块编写rspec时,我不想使用我现有的模型.
使用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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读