【问题标题】:RSpec & Custom matcher with multiple arguments具有多个参数的 RSpec 和自定义匹配器
【发布时间】:2013-04-21 20:32:01
【问题描述】:

我正在尝试使用 RSpec 为我在 RoR 中的测试创建自定义匹配器。

  define :be_accessible do |attributes|
    attributes = attributes.is_a?(Array) ? attributes : [attributes]
    attributes.each do |attribute|
      match do |response|
        response.class.accessible_attributes.include?(attribute)
      end
      description { "#{attribute} should be accessible" }
      failure_message_for_should { "#{attribute} should be accessible" }
      failure_message_for_should_not { "#{attribute} should not be accessible" }
    end
  end

我希望能够在我的测试中编写如下内容:

...
should be_accessible(:name, :surname, :description)
...

但是使用上面定义的匹配器,我必须传递一个符号数组而不是用逗号分隔的符号,否则测试只检查第一个符号。

有什么想法吗?

【问题讨论】:

  • 这是一个应该符合您的第一个需求的答案:stackoverflow.com/a/4643289/582863。无论如何,我很好奇你在这里的意图......你只是想减少 rspec 测试文件中的行数,还是你在模型属性上测试复杂的可访问性?
  • 您提供的链接的问题是这不是“常规” def 方法,所以我不能使用 *.回答你的问题,我只是想减少我的 rspec 行:)

标签: ruby-on-rails ruby ruby-on-rails-3 rspec


【解决方案1】:

我是这样设计的:

RSpec::Matchers.define :be_accessible do |*attributes|
  match do |response|

    description { "#{attributes.inspect} be accessible" }

    attributes.each do |attribute|
      failure_message_for_should { "#{attribute} should be accessible" }
      failure_message_for_should_not { "#{attribute} should not be accessible" }

      break false unless response.class.accessible_attributes.include?(attribute)
    end
  end
end

我反转了 matcheach 循环。我认为这是 Rspec 期望的方式,因为给 match 方法的块是由 Rspec 抽象匹配器执行的块(我猜)。

通过使用|*attributes| 定义块,它获取参数列表并将其转换为Array

所以调用should be_accessible(:name, :surname, :description) 就可以了。

顺便说一句,如果你只是想检查属性是否存在,一个简单的

should respond_to(:name, :surname, :description)

也可以。但它看起来不像批量分配方面。

【讨论】:

  • 它有效,感谢您的时间!我想检查批量分配,所以您的解决方案就是我需要的解决方案。
  • 这确实帮助了我,但是当我根据自己的情况调整这个例子时,我发现它只适用于积极的期望(不适用于 should_not as-is)。我必须创建单独的 match_for_shouldmatch_for_should_not 块,如下所示:relishapp.com/rspec/rspec-expectations/v/3-0/docs/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多