RSPECの例を挿入するメソッドを作成するにはどうすればよいですか?
-
09-10-2019 - |
質問
RSPEC Railsユニットの仕様の束で、私は次のようなことをします:
describe Foo do
[:bar, :baz].each do |a|
it "should have many #{a}" do
Foo.should have_many(a)
end
end
end
クリーナーコードについては、次のようなことをしたいです。
describe Foo do
spec_has_many Foo, :bar, :baz
end
では、次のようなヘルパーメソッドを書くにはどうすればよいですか spec_has_many()
RSPECのようなDSLコードを挿入するため it()
方法?それが通常のインスタンス方法の場合、私は次のようなことをします:
def spec_has_many(model, *args)
args.each do |a|
define_method("it_should_have_many_#{a}") do
model.should have_many(a)
end
end
end
RSPECの例を定義するのに相当するものは何ですか?
解決
わかりました、これには少しの混乱がかかりましたが、私はそれを機能させたと思います。それは少しメタプログラムハッカーであり、私はあなたが最初に説明したものを個人的に使用するだけですが、それはあなたが望んでいたものです:P
module ExampleMacros
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
# This will be available as a "Class Macro" in the included class
def should_have_many(*args)
args.each do |a|
# Runs the 'it' block in the context of the current instance
instance_eval do
# This is just normal RSpec code at this point
it "should have_many #{a.to_s}" do
subject.should have_many(a)
end
end
end
end
end
end
describe Foo do
# Include the module which will define the should_have_many method
# Can be done automatically in RSpec configuration (see below)
include ExampleMacros
# This may or may not be required, but the should_have_many method expects
# subject to be defined (which it is by default, but this just makes sure
# it's what we expect)
subject { Foo }
# And off we go. Note that you don't need to pass it a model
should_have_many :a, :b
end
fooがないため、私の仕様は失敗します has_many?
方法ですが、両方のテストが実行されるため、動作するはずです。
あなたはあなたのexamplemacrosモジュールを定義(および名前変更)することができます spec_helper.rb
ファイルとそれは含めることができます。あなたは電話したい include ExampleMacros
あなたの中で describe
ブロック(他のものではありません)。
すべての仕様を作成するには、モジュールを自動的に含めるには、次のようにrspecを構成します。
# RSpec 2.0.0
RSpec.configure do |c|
c.include ExampleMacros
end
所属していません StackOverflow