mardi 28 mars 2017

Why adding association mark my model as not valid?

I'm developing a simple weather API in Rails. This API will give the forecast for a given day. The forecast will have hourly data about the wind, temperature, relative humidity, etc.

I have implemented a model for the Forecast. The forecast have an association "has_many" with the other models, for example, the Wind. I have developed the following model for the Wind object:

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

As I am trying to use TDD, I have implemented the following tests (among others):

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

This bunch of tests was passing before I add the association with forecast:

belongs_to :forecast, foreign_key: true

Indeed, if I remove that line, any test fails. But with that line in the model, the following tests are failing (they are false and the test expects 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

I am trying to understand why this is happening. Anyone knows why those tests are failing? Also, is there any proper way to test associations?

Thank you in advance.

Aucun commentaire:

Enregistrer un commentaire