【问题标题】:Automatically test formats in Rails functional tests在 Rails 功能测试中自动测试格式
【发布时间】:2012-09-08 03:50:17
【问题描述】:

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

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”。

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

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

【问题讨论】:

    标签: ruby-on-rails ruby binding functional-testing


    【解决方案1】:

    以下内容对我有用:

    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
    

    【讨论】:

    • 这是一个很好的解决方案,但您还发布了一个可能比某些人更可取的早期解决方案。我会把它作为后代的另一个答案发布。
    【解决方案2】:

    此代码最初是作为 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
    

    【讨论】:

      猜你喜欢
      • 2010-12-27
      • 2012-05-30
      • 1970-01-01
      • 1970-01-01
      • 2011-06-29
      • 2011-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多