【发布时间】:2017-03-28 21:09:41
【问题描述】:
我正在 Rails 中开发一个简单的天气 API。此 API 将提供给定日期的预测。预报将有关于风、温度、相对湿度等的每小时数据。
我已经为 Forecast 实现了一个模型。预测与其他模型(例如 Wind)有关联“has_many”。我为 Wind 对象开发了以下模型:
class Wind < ApplicationRecord
belongs_to :forecast, foreign_key: true
validates_presence_of :period
validates :velocity, numericality: true, allow_blank: true
validates :direction, length: { maximum: 2 }, allow_blank: true
end
当我尝试使用 TDD 时,我已经实现了以下测试(以及其他测试):
class WindTest < ActiveSupport::TestCase
setup do
@valid_wind = create_valid_wind
@not_valid_wind = create_not_valid_wind
end
test 'valid_wind is valid' do
assert @valid_wind.valid?
end
test 'valid_wind can be persisted' do
assert @valid_wind.save
assert @valid_wind.persisted?
end
test 'not_valid_wind is not valid' do
assert_not @not_valid_wind.valid?
end
test 'not valid wind cannot be persisted' do
assert_not @not_valid_wind.save
assert_not @not_valid_wind.persisted?
end
test 'not_valid_wind has error messages for period' do
assert_not @not_valid_wind.save
assert_not @not_valid_wind.errors.messages[:period].empty?
end
test 'not_valid_wind has error messages for velocity' do
assert_not @not_valid_wind.save
assert_not @not_valid_wind.errors.messages[:velocity].empty?
end
test 'not_valid_wind has error messages for direction' do
assert_not @not_valid_wind.save
assert_not @not_valid_wind.errors.messages[:direction].empty?
end
private
def create_valid_wind
valid_wind = Wind.new
valid_wind.direction = 'NO'
valid_wind.velocity = 2
valid_wind.period = '00-06'
valid_wind.forecast_id = forecasts(:one).id
valid_wind
end
def create_not_valid_wind
not_valid_wind = Wind.new
not_valid_wind.velocity = 'testNumber'
not_valid_wind.direction = '123'
not_valid_wind
end
end
在我添加与预测的关联之前,这一系列测试已经通过:
belongs_to :forecast, foreign_key: true
确实,如果我删除该行,任何测试都会失败。但是对于模型中的那条线,以下测试失败(它们是错误的,测试期望为真):
test 'valid_wind is valid' do
assert @valid_wind.valid?
end
test 'valid_wind can be persisted' do
assert @valid_wind.save
assert @valid_wind.persisted?
end
我试图了解为什么会发生这种情况。任何人都知道为什么这些测试失败了?另外,有什么合适的方法来测试关联吗?
提前谢谢你。
【问题讨论】:
标签: ruby-on-rails ruby testing tdd minitest