ruby 用于匹配accept_nested_attributes_for的RSpec匹配器

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 用于匹配accept_nested_attributes_for的RSpec匹配器相关的知识,希望对你有一定的参考价值。

  # Use: it { should accept_nested_attributes_for(:association_name).and_accept({valid_values => true}).but_reject({ :reject_if_nil => nil })}
  RSpec::Matchers.define :accept_nested_attributes_for do |association|
    match do |model|
      @model = model
      @nested_att_present = model.respond_to?("#{association}_attributes=".to_sym)
      if @nested_att_present && @reject
        model.send("#{association}_attributes=".to_sym,[@reject])
        @reject_success = model.send("#{association}").empty?
      end
      model.send("#{association}").clear
      if @nested_att_present && @accept
        model.send("#{association}_attributes=".to_sym,[@accept])
        @accept_success = ! (model.send("#{association}").empty?)
      end
      @nested_att_present && ( @reject.nil? || @reject_success ) && ( @accept.nil? || @accept_success )
    end
    
    failure_message_for_should do
      messages = []
      messages << "accept nested attributes for #{association}" unless @nested_att_present
      messages << "reject values #{@reject.inspect} for association #{association}" unless @reject_success
      messages << "accept values #{@accept.inspect} for association #{association}" unless @accept_success
      "expected #{@model.class} to " + messages.join(", ")
    end
    
    description do
      desc = "accept nested attributes for #{expected}"
      if @reject
        desc << ", but reject if attributes are #{@reject.inspect}"
      end
    end
    
    chain :but_reject do |reject|
      @reject = reject
    end
    
    chain :and_accept do |accept|
      @accept = accept
    end
  end

以上是关于ruby 用于匹配accept_nested_attributes_for的RSpec匹配器的主要内容,如果未能解决你的问题,请参考以下文章

ruby 用于匹配accept_nested_attributes_for的RSpec匹配器

ruby 用于匹配accept_nested_attributes_for的RSpec匹配器

Ruby Dir 类和方法

如何获取字符串中所有出现的 Ruby 正则表达式的匹配数据?

用于构建成就系统的现代 Ruby/Rails 工具

Puppet正则表达式(十七)