为什么添加关联标记我的模型无效?

时间:2017-03-28 21:09:41

标签: ruby-on-rails ruby testing tdd minitest

我正在开发Rails中的简单天气API。此API将提供给定日期的预测。预测将包含有关风,温度,相对湿度等的每小时数据。

我已经为预测实施了一个模型。预测与其他模型有关联“has_many”,例如Wind。我为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

我试图理解为什么会这样。任何人都知道为什么那些测试失败了?另外,有没有适当的方法来测试关联?

提前谢谢。

1 个答案:

答案 0 :(得分:0)

test 'valid_wind can be persisted' do
  assert @valid_wind.save
  assert @valid_wind.persisted?
end

这个测试几乎毫无价值,因为你只是测试测试设置是否正确,它没有告诉你测试中的应用程序。

相反,在模型测试中,您应该在每个验证的基础上进行测试:

test 'does not allow non numerical values for velocity' do
  wind = Wind.new(velocity: 'foo')
  wind.valid?
  assert_match "is not a number", wind.errors.full_messages_for(:velocity)
end

test 'allows numerical values for velocity' do
  wind = Wind.new(velocity: 3)
  wind.valid?
  refute(wind.errors.include?(:velocity))
end

测试传递值通常只是略微有用,但如果出现错误则可能很有价值。

在您的模型中,您并不需要担心设置完全有效的记录 - 无论如何,您的功能和集成测试都将涵盖在内。

相关问题