0

我想让我的每个功能测试自动测试各种格式。似乎实现这一点的方法是将“测试”方法包装在我自己的类方法中:

def self.test_all_formats(name)
  [ "xml", "json" ].each do |fmt|
    test "#{name} #{fmt}" do
      yield(format)
    end
  end
end

test_all_formats "index" do |fmt|
  get :index, { :format => fmt }
  assert_response :ok
end

不幸的是,每个测试都会引发以下错误:

NoMethodError:AccountsControllerTest:Class 的未定义方法“get”。

尽管块的执行被推迟到测试的执行,但它试图在类的上下文中而不是实例的上下文中运行块。

有没有办法实现这种自动化测试?

4

2 回答 2

0

以下对我有用:

class << self
  def test_all_formats(name, &block)
    [ "xml", "json" ].each do |fmt|
      test "#{name} #{fmt}" do
        instance_exec fmt, &block
      end
    end
  end
end

test_all_formats "index" do |fmt|
  get :index, { :format => fmt }
  assert_response :ok
end
于 2012-09-15T05:21:41.813 回答
0

此代码最初是作为 Chris Oei 的解决方案提供的,如果您不喜欢使用 instance_exec,可能会更可取:

class << self
   def test_formats(name, &block)
    define_method "fmt_#{name}", &block
      [ "xml", "json" ].each do |fmt|
        test "#{name} #{fmt}" do
          send "fmt_#{name}", fmt
        end
      end
    end
  end
end
于 2012-09-21T17:52:55.600 回答