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

覆盖自定义验证

  •  0
  • Obromios  · 技术社区  · 7 年前

    ruby on rails player games .但是,玩家至少应该有三场比赛。我有一个自定义验证器,如果没有三个游戏,它会增加错误。我可以通过在 模型

    accepts_nested_attributes_for :games
    

    运动员

    rspec 类似代码

    player = create: :player
    game = create :game
    player.games << game
    

    create :player

    有办法吗?如果我不能做到这一点,我只能通过构建一个嵌套的散列来测试对特定游戏的敏感性,这使得很难看到测试在做什么,因为密钥更改在散列中很深。

    2 回复  |  直到 7 年前
        1
  •  0
  •   Jagdeep Singh    7 年前

    修改您的rspec以尊重验证。

    let(:player) { build(:player) }
    let(:game) { create(:game) }
    let(:another_game) { create(:game) }
    let(:one_more_game) { create(:game) }
    
    it 'test something' do
      player.games += [game]
    
      # Do your stuff
    
      player.games += [another_game]
    
      # Do some more stuff
    
      player.games += [one_more_game]
    
      # and now that `player` object is valid, you can do:
      player.save!
    
      # Check your expectations here
    end
    

    注:

    • player 没有游戏的对象,我正在构建
    • let .它们更适合RSPEC。

        2
  •  0
  •   htunc    7 年前

    可以使用自定义方法来持久化对象

    factory :player do
      to_create {|instance| instance.save(validate: false) }
    end
    

    https://github.com/thoughtbot/factory_bot/blob/master/GETTING_STARTED.md#custom-methods-to-persist-objects