2

ActiveSupport::Concern を拡張するモジュールがあります。includedブロックは次のとおりです。

included do
  after_save :save_tags

  has_many :taggings, :as => :taggable
  has_many :tags, :through => :taggings
end

これらの呼び出しをスタブするにはどうすればよいですか? いくつかの方法を試しましたが、Ruby は、モジュールを単独でテストしようとすると、これらのメソッドが存在しないと文句を言います。

ありがとう!

4

2 に答える 2

3

テストしたいものに応じて、いくつかのオプションがあると思います。

has_manyモジュールが実際にアソシエーションを設定してコールバックすることをテストしたいだけの場合はafter_save、単純な rspec 期待値を設定できます。

class Dummy
end

describe Taggable do
  it "should setup active record associations when included into models" do
    Dummy.should_receive(:has_many).twice
    Dummy.should_receive(:after_save).with(:save_tags)
    Dummy.send(:include, Taggable) # send is necessary because it's a private method
  end
end

おそらくsave_tags、それ以上のモックを作成しなくてもメソッドを非常に簡単にテストできますが、設定されている has_many アソシエーションに依存する動作をテストしたい場合は、has_many と after_save をスタブ化した別の Dummy クラスを作成できますが、アソシエーションのアクセサーを使用します。

class Dummy
  attr_accessor :taggings, :tags

  # stub out these two
  def self.has_many
  end

  def self.after_save
  end

  def initialize
    @taggings = []
    @tags = []
  end

  include Taggable
end

describe Taggable do
  it "should provide a formatted list of tags, or something" do
     d = Dummy.new
     d.tags = [double('tag')]
     d.formatted_tags.size.should == 1
  end
end

少々のメタ プログラミングでそれ (やや脆いテスト クラス) をきれいにすることができますが、これがテストを理解するのを難しくするかどうかはあなたの判断次第です。

class Dummy
  def self.has_many(plural_object_name, options={})
    instance_var_sym = "@#{plural_object_name}".to_sym

    # Create the attr_reader, setting the instance var if it doesn't exist already
    define_method(plural_object_name) do
      instance_variable_get(instance_var_sym) ||
          instance_variable_set(instance_var_sym, [])
    end

    # Create the attr_writer
    define_method("#{plural_object_name}=") do |val|
      instance_variable_set(instance_var_sym, val)
    end
  end

  include Taskable
end
于 2012-12-20T20:07:09.620 に答える
0

テストを開始する前に、最初に ActiveSupport::Concern の元の定義を含むファイルをロードする必要があります。その後、拡張機能をロードする必要があります。Rails のオートローディング メカニズムが元のエクステンションを優先してエクステンションを検出するため、必ず正しいファイルをロードしてください。

于 2011-05-31T18:46:56.683 に答える