ruby-on-rails – 测试:在anaf中的reject_if

我有一个用户模型
class User < ActiveRecord::Base
  has_many :languages,:dependent => :destroy
  accepts_nested_attributes_for :languages,:reject_if => lambda { |l| l[:name].blank? }
end

我想用RSpec 2.0.0测试reject_if部分.目前我有两个简单的测试用例

it "should not save language without name by accepts_nested_attributes" do
    lambda {
      @user.update_attributes!("languages_attributes"=>{"0"=>{}})
    }.should_not change(Language,:count)
  end

  it "should save language with name by accepts_nested_attributes" do
    lambda {
      @user.update_attributes!("languages_attributes"=>{"0"=>{"name"=>"lang_name"}})
    }.should change(Language,:count).by(1)
  end

但是我对测试很新,看起来很奇怪.
我想知道这是否是测试reject_if的正确方法?有没有更好的方法呢?

解决方法

我看到你要测试reject_if然后最好的方法是直接测试它:
anaf_for_languages = User.nested_attributes_options[:languages]
anaf_for_languages[:reject_if].call({ "name" => "" }).should be_true

如果是,则名称为空.我认为这比你的代码更简洁,但不是那么明显.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...