【发布时间】:2016-03-11 20:49:14
【问题描述】:
我有一个这样定义的关注点:
module Shared::Injectable
extend ActiveSupport::Concern
module ClassMethods
def injectable_attributes(attributes)
attributes.each do |atr|
define_method "injected_#{atr}" do
...
end
end
end
end
以及像这样使用关注点的各种模型:
Class MyThing < ActiveRecord::Base
include Shared::Injectable
...
injectable_attributes [:attr1, :attr2, :attr3, ...]
...
end
这按预期工作,并生成一组我可以在类的实例上调用的新方法:
my_thing_instance.injected_attr1
my_thing_instance.injected_attr2
my_thing_instance.injected_attr3
当我尝试测试问题时,我的问题就出现了。我想避免为每个使用关注点的模型手动创建测试,因为生成的函数都做同样的事情。相反,我认为我可以使用 rspec 的 shared_example_for 并编写一次测试,然后使用 rspec 的 it_should_behave_like 在必要的模型中运行测试。这很好用,但我在访问已传递给 injectable_attributes 函数的参数时遇到问题。
目前,我在共享规范中这样做:
shared_examples_for "injectable" do |item|
...
describe "some tests" do
attrs = item.methods.select{|m| m.to_s.include?("injected") and m.to_s.include?("published")}
attrs.each do |a|
it "should do something with #{a}" do
...
end
end
end
end
这可行,但显然是一种可怕的方法。有没有一种简单的方法可以只访问传递给 injectable_attributes 函数的值,无论是通过类的实例还是通过类本身,而不是查看已经在类实例上定义的方法?
【问题讨论】:
标签: ruby-on-rails ruby rspec activesupport-concern