gpt4 book ai didi

ruby-on-rails - 测试 :reject_if in anaf

转载 作者:行者123 更新时间:2023-12-04 03:45:09 24 4
gpt4 key购买 nike

我有一个用户模型

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

如果是 true ,然后 name是空白。我认为这比您的代码更简洁,但并不那么明显。

关于ruby-on-rails - 测试 :reject_if in anaf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4433823/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com