ruby-on-rails - 比较长文本(使用\t 和\n)时如何很好地格式化自动测试和 RSpec?

标签 ruby-on-rails testing formatting rspec autotest

我在 RSpec 中有一个与长文本字符串进行比较的测试。当测试失败时,我会收到这样的消息:

'jobs partial should render the correct format for jobs' FAILED
expected: "Job {\n\tName = \"name1-etc\"\n\tType = Backup\n\tMessages = Daemon\n\tPool = Default
\n\tSchedule = \"schedule1\"\n\tStorage = storage1\n\tClient = \"name1\"\n\tFileset = \"fileset1
\"\n\tMax Wait Time = 5m\n\tWrite Bootstrap = \"/var/lib/bacula/name1-etc.bsr\"\n}\n\n",
     got: "Job {\n\tName = \"name1-etc\"\n\tType = Backup\n\tMessages = Daemon\n\tPool = Default
\n\tSchedule = \"schedule1\"\n\tStorage = storage1\n\tClient = \"name1\"\n\tFileset = \"fileset1
\"\n\tMax Wait Time = 5m\n\tWrite Bootstrap = \"/var/lib/bacula/name1-etc.bsr\"\n}\n\n" (using =
=)

我该怎么做才能使 RSpec 和自动测试响应格式良好的差异(如果可能的话,为文本之间的差异着色?像这样

expected:
Job {
    Name = "name1-etc"
    Type = Backup
    Messages = Daemon
    Pool = Default
    Schedule = "schedule1"
    Storage = storage1
    Client = "name1"
    Fileset = "fileset1" <--diff
    Max Wait Time = 5m
    Write Bootstrap = "/var/lib/bacula/name1-etc.bsr"
}
got:
Job {
    Name = "name1-etc"
    Type = Backup
    Messages = Daemon
    Pool = Default
    Schedule = "schedule1"
    Storage = storage1
    Client = "name1"
    Fileset = "fileset2" <-- diff
    Max Wait Time = 5m
    Write Bootstrap = "/var/lib/bacula/name1-etc.bsr"
}

最佳答案

我找到的最佳解决方案是:

module CustomMatchers
    class HaveTheSameText
      def initialize(expected)
        @expected = expected
      end

      def matches?(actual)
        @actual = actual
        @actual == @expected
      end

      def failure_message
        `diff #{file_for @expected} #{file_for @actual}`
      end

      def negative_failure_message
        "don't apply"
      end

    private
      def   file_for text
        exp = Tempfile.new("bk", "/tmp").open
        exp.write(text)
        exp.close
        exp.path
      end
    end

    def have_the_same_text_of(expected)
      HaveTheSameText.new(expected)
    end
end

在我的规范中我使用

actual.should have_the_same_text_of expected

关于ruby-on-rails - 比较长文本(使用\t 和\n)时如何很好地格式化自动测试和 RSpec?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1509473/

相关文章:

testing - 在 Appium 中按下 android 菜单按钮

reactjs - Jest React Native 如何测试 index.PLATFORM.js

arrays - 在PowerShell中到数组的字符串(无定界符)

java - 如何格式化 double 型变量

ruby-on-rails - RESTful API 最佳实践,更新与自定义操作

ruby-on-rails - Rails 3 路由问题

ruby-on-rails - 如何使用 rake 命令在命名空间的每个任务上运行一个函数

testing - rspec 模拟外部 api

google-apps-script - 如何通过 Apps 脚本在 Google 表格中显示 "Clear Format"

ruby-on-rails - ruby 在 rails 上。通过 View 更改 Controller 的变量并渲​​染更新的 View