代码之家  ›  专栏  ›  技术社区  ›  BvuRVKyUVlViVIc7

验证与RSPEC相关联的_,并验证_是否存在不按预期工作?

  •  6
  • BvuRVKyUVlViVIc7  · 技术社区  · 17 年前

    我有一个用户模型和一个友谊模型。

    class Friendship < ActiveRecord::Base
      belongs_to :sender, :class_name=>'User', :foreign_key=>'sender_id'
      belongs_to :receiver, :class_name=>'User', :foreign_key=>'receiver_id'
    
      validates_presence_of :receiver_id, :sender_id
      validates_associated :receiver, :sender
    end
    
    class User < ActiveRecord::Base
      has_many :sent_friendships, :class_name => "Friendship", :foreign_key => "sender_id", :dependent => :destroy
      has_many :received_friendships, :class_name => "Friendship", :foreign_key => "receiver_id", :dependent => :destroy
    end
    

    我的一个RSPEC测试是

    describe Friendship do
    
      before(:each) do
        @valid_attributes = {
          :sender_id => 1,
          :receiver_id => 2,
          :accepted_at => nil
        }
      end
    
      it "should not be valid with non-existant receiver_id" do
        f = Friendship.new(@valid_attributes)
        f.receiver_id = 99999
        f.should_not be_valid
      end
    end
    

    测试不应有效,因为没有用户具有用户ID 9999。但测试说的是友谊模式是有效的。

    为什么是地狱?

    编辑:

    但是我想像前面提到的那样进行测试--不直接分配发送者。这不可能吗??

    4 回复  |  直到 17 年前
        1
  •  11
  •   Elliot Nelson    17 年前

    如果您希望您的模型以这种方式工作,请更改此项:

    validates_presence_of :receiver_id, :sender_id
    

    对此:

    validates_presence_of :receiver, :sender
    
        2
  •  2
  •   Christoph Schiessl Joeyjoejoejr    17 年前

    Rails文档 validates_associtated 声明如下:

    注意:如果尚未分配关联,则此验证不会失败。如果要确保关联既存在又保证有效,则还需要使用验证存在。

    你没有分配协会。按以下方式修改测试,它应该通过:

    it "should not be valid with non-existant receiver_id" do
      f = Friendship.new(@valid_attributes)
      f.receiver_id = 99999
      f.receiver = nil  # Note this line
      f.should_not be_valid
    end
    
        3
  •  2
  •   Ian Terrell    17 年前

    还有一个老的插件在周围浮动,这样做… validates_existence_of .

    http://blog.hasmanythrough.com/2007/7/14/validate-your-existence

        4
  •  1
  •   BvuRVKyUVlViVIc7    17 年前

    Hm.。

    在我在Rails灯塔找到这个博客条目和一张不固定的票之后:

    Blog-entry with solution

    Lighthouse-wont-fix-ticket

    我转向自己的解决方案:

    class Friendship < ActiveRecord::Base
      belongs_to :sender, :class_name=>'User', :foreign_key=>'sender_id'
      belongs_to :receiver, :class_name=>'User', :foreign_key=>'receiver_id'
    
      validates_presence_of :receiver_id, :sender_id
    
      validate :sender_exists
      validate :receiver_exists
    
      protected
      def sender_exists
        errors.add("sender_id", "not existant") unless User.exists?(self.sender_id)
      end  
    end
    
    推荐文章