dim*_*nyc 1 ruby validation rspec ruby-on-rails
我正在为控制器POST #update/ with invalid attributes上下文编写规范:
context 'with invalid attributes' do
it "does not change @foo's attributes with empty params" do
expect(patch :update, id: @foo, foo: attributes_for(:foo,
start_time: nil,
end_time: nil)
).to raise_error('ActiveRecord::RecordInvalid')
end
end
Run Code Online (Sandbox Code Playgroud)
validates :name, presence: true
validate :dates_logic_validation
Run Code Online (Sandbox Code Playgroud)
def dates_logic_validation
if !start_time.present? || start_time.nil?
errors.add(:start_time, "Please double check the starting time")
elsif !end_time.present? || end_time.nil?
errors.add(:end_time, "Please double check the starting time")
elsif (start_time.to_datetime rescue ArgumentError) == ArgumentError
errors.add(:start_time, 'Please double check the Start Time format')
elsif (end_time.to_datetime rescue ArgumentError) == ArgumentError
errors.add(:end_time, 'Please double check the End Time format')
elsif start_time < Time.now
errors.add(:start_time, 'Start time must be greater or equal to today\'s date')
elsif start_time > end_time
errors.add(:end_time, 'End time must be greater than start time')
end
end
Run Code Online (Sandbox Code Playgroud)
由于某种原因,上面的规范仍然返回ActiveRecord错误/Validation failed: Start time Please double check the starting time
使用raise_error匹配器时,需要将括号更改为花括号.
示例:
expect { raise "oops" }.to raise_error(RuntimeError)
Run Code Online (Sandbox Code Playgroud)
资料来源:https://www.relishapp.com/rspec/rspec-expectations/v/3-1/docs/built-in-matchers/raise-error-matcher