gpt4 book ai didi

rspec - 如何使用 rspec-rails 3.0.0 和 shoulda-matchers 2.5.0 测试条件验证

转载 作者:行者123 更新时间:2023-12-04 18:55:23 25 4
gpt4 key购买 nike

我正在使用 rspec-rails 3.0.0 和 shoulda-matchers 2.5.0 运行 Rails 4 应用程序,并且我有一个事件模型,它具有一些条件验证,如下所示:

class Event < ActiveRecord::Base
validates :name, :location, :time, :city, :zipcode, :user, :state, presence: true
validates :post_text, presence: true, if: :happened?
validates :pre_text, presence: true, unless: :happened?

belongs_to :community
belongs_to :user
belongs_to :state

def happened?
(self.time < Time.now) ? true : false
end
end

我的 event_spec.rb 看起来像:
require 'spec_helper'

describe Event do
before { @event = FactoryGirl.build(:future_event) }

subject { @event }

it { should validate_presence_of(:time) }
it { should validate_presence_of(:name) }
it { should validate_presence_of(:location) }
it { should validate_presence_of(:user) }
it { should validate_presence_of(:city) }
it { should validate_presence_of(:state) }
it { should validate_presence_of(:zipcode) }

it { should belong_to(:state) }
it { should belong_to(:user) }

it 'has pre_text if future event' do
expect(FactoryGirl.create(:future_event)).to be_valid
end

it 'has post_text if past event' do
expect(FactoryGirl.create(:past_event)).to be_valid
end
end

但是当我运行测试时,我的 it { should validate_presence_of(:time) }块失败,因为它继续运行剩余的验证并在条件验证上抛出异常,因为 self.time 为零。我已经通过检查 time.present 对此实现了一个hacky修复?在发生什么?方法。但是谁能帮助我了解测试需要另一个字段存在的条件验证的最佳方法是什么?

最佳答案

这肯定来晚了,但对于其他正在寻找解决方案的人来说。我找到了一种有效的方法:

context "if happened" do
before { allow(subject).to receive(:happened?).and_return(true) }
it { is_expected.to validate_presence_of(:time) }
end

我希望这有帮助

关于rspec - 如何使用 rspec-rails 3.0.0 和 shoulda-matchers 2.5.0 测试条件验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22156073/

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