2012-09-15 69 views
0

我想让我的每个功能测试自动测试各种格式。这似乎喜欢的方式来实现这一目标是收官“测试”法在我自己的类方法:在Rails功能测试中自动测试格式

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: undefined method `get' for AccountsControllerTest:Class.

虽然执行的块被推迟到测试执行之前,它试图在类的上下文而不是实例上运行该块。

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

回答

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 
+0

这是一个很好的解决方案,但你还发布了一个早期的解决方案,可能比一些更好。我会把它作为后代的另一个答案。 –

0

此代码克里斯黄曼迪的溶液最初提供,并可能是最好,如果你不喜欢使用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