【发布时间】:2021-10-19 18:12:39
【问题描述】:
我是 Rails 新手,我有一个带有三个外键的 trip 课程。其中两个将其与同一类相关联:Place。
这是我的模型:
class Trip < ApplicationRecord
belongs_to :from, class_name: "Place", foreign_key: "from_id"
belongs_to :to, class_name: "Place", foreign_key: "to_id"
belongs_to :vehicle, class_name: "Vehicle", foreign_key: "vehicle_id"
validates :price, presence: true
validates :time, presence: true
validates :from_id, presence: true
validates :to_id, presence: true, if: :from_different_to?
def from_different_to?
to_id != from_id
end
end
除最后一项外,所有模型测试均通过:
class TripTest < ActiveSupport::TestCase
def setup
@place1 = Place.create(name:"NewYork",cap:"11111",lat:"1234",long:"1478")
@place2 = Place.create(name:"Los Angeles", cap:"22222", lat:"1234",long:"1478")
@vehicle = Vehicle.create(targa: "ab123cd",modello:"500",marca:"Fiat", posti:5,alimentazione:"benzina")
@trip = Trip.new(price: 10, time: Time.new(2021, 10, 14, 12,03), from_id: @place1.id, to_id: @place2.id,vehicle_id: @vehicle.id)
end
...
test "Departure id and arrival id should be different" do
@trip.to_id = @place1.id
assert_not @trip.valid?
end
导致失败的:
Failure:
TripTest#test_Departure_id_and_arrival_id_should_be_different [/media/alessandro/DATA/Universita/Magistrale/1_anno/Programmazione_concorrente/hitchhiker/test/models/trip_test.rb:45]:
Expected true to be nil or false
我无法理解为什么。 有人可以帮我吗?
【问题讨论】:
-
@spickermann 记录是有效的,但他们希望它不是。我不知道为什么。
-
@spickermann 在设置中我设置了
to_id: @place2.id,但在测试中我设置了@trip.to_id = place1.id,所以to_id == from_id == @place1.id。这是因为如果模型有效拒绝此记录,我想尝试一次无效的旅行
标签: ruby-on-rails ruby testing