私はRailsで簡単な天気APIを開発しています。このAPIは、特定の日の予測を提供します。予測には、風、気温、相対湿度などに関する毎時のデータがあります。アソシエーションを追加すると、私のモデルは無効とマークされるのはなぜですか?
私はForecastのモデルを実装しました。予測には、他のモデル、たとえば風との関連性「has_many」があります。私はTDDを使用しようとしていますとして
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
、私は(特に)次のテストを実施している:私は、風オブジェクトの以下のモデルを開発した
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
私はこれが起こっている理由を理解しようとしています。なぜ誰もそのテストが失敗していることを知っていますか?また、関連性をテストするための適切な方法はありますか?
ありがとうございます。
'belongs_to:forecast'を使うとどうなりますか? – DiodonHystrix
アソシエーションをテストするには、フィクスチャを使用できます。このチュートリアル(https:// semaphoreci.com/community/tutorials/how-to-test-rails-models-with-minitest')を試してみてください。 – DiodonHystrix
@DiodonHystrix foreign_key:trueを削除すると、テストは機能しています。なぜこうなった? foreign_keyを削除するのは正しいです:true?アソシエーションテストのチュートリアルのおかげで:) – F404