【问题标题】:Rspec custom failure message error when match runs matchers匹配运行匹配器时Rspec自定义失败消息错误
【发布时间】:2012-08-29 16:06:32
【问题描述】:

我正在使用 Steak 进行验收测试,因为我根本不喜欢 Cucumber,尽管我在测试的方式中使用了一些 Cucumber 概念。我喜欢声明式和命令式的测试风格,我将一些期望抽象到精心设计的自定义 rspec 匹配器中,这些匹配器在 match 方法中使用其他匹配器,下面是一个示例:

RSpec::Matchers.define :show_post do |post|
  match do |page|
    within '.post' do
      page.should have_content post.title
      page.should have_content post.tagline
      page.should have_content post.body
      page.should list_author  post.author
    end
  end
end

我遇到的唯一问题是,如果我的匹配器失败,我会收到一条通用消息,无法让我了解缺少的内容,而我现在真正想要的是组成自定义匹配器的期望之一不满足。

我已经忍受这种麻烦有一段时间了,因为我真的很喜欢能够做到的表现力:

page.should show_post Post.last

【问题讨论】:

    标签: ruby-on-rails rspec capybara


    【解决方案1】:

    知道了:

    class ShowsPost
      include Capybara::RSpecMatchers
    
      def initialize post
        @post = post
      end
    
      def matches? page
        page.should have_content @post.title
        page.should have_content @post.tagline
        page.should have_content @post.body
        page.should list_author  @post.author
      end
    end
    
    def show_post post
      ShowsPost.new(post)
    end
    

    【讨论】:

    • 虽然不理想,因为我更喜欢宏来制作匹配器。
    【解决方案2】:

    更好:

    module DefineMatcher
      def define_matcher name, &block
        klass = Class.new do
          include Capybara::RSpecMatchers
    
          attr_reader :expected
    
          def initialize expected
            @expected = expected
          end
    
          define_method :matches?, &block
        end
    
        define_method name do |expected|
          klass.new expected
        end
      end
    end
    
    
    module PageMatchers
      extend DefineMatcher
    
      define_matcher :show_notice do |page|
        within '.alert-notice' do
          page.should have_content expected
        end
      end
    end
    
    RSpec.configuration.include PageMatchers, :type => :acceptance
    

    【讨论】:

      猜你喜欢
      • 2017-02-24
      • 1970-01-01
      • 1970-01-01
      • 2015-01-16
      • 2013-07-02
      • 2019-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多