テストしたいものに応じて、いくつかのオプションがあると思います。
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