来自Rails世界中的测试,在rspec中有一种简单的方法可以测试模型关系是否正确设置:
require 'spec_helper'
RSpec.describe Country, type: :model do
it {is_expected.to have_many :cities}
end
如何为使用SQL Alchemy在Flask应用程序中创建的这些模型编写关系测试?
class City(SurrogatePK, Model):
"""
https://dev.mysql.com/doc/sakila/en/sakila-structure-tables-city.html
city_id: A surrogate primary key used to uniquely identify each city in the table.
city: The name of the city.
country_id: A foreign key identifying the country that the city belongs to.
last_update: The time that the row was created or most recently updated.
"""
__tablename__ = 'cities'
city = Column(db.String(50), nullable=False)
country_id = reference_col('countries', nullable=True)
country_id = db.Column(db.Integer, db.ForeignKey('countries.id'),nullable=False)
last_update = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow)
country = db.relationship('Country', foreign_keys= [country_id], backref='cities', lazy=True)
def __repr__(self):
"""Represent instance as a unique string."""
return '<City ({city})>'.format(city=self.city)
class Country(SurrogatePK, Model):
"""
https://dev.mysql.com/doc/sakila/en/sakila-structure-tables-country.html
country_id: A surrogate primary key used to uniquely identify each country in the table.
country: The name of the country.
last_update: The time that the row was created or most recently updated.
"""
__tablename__ = 'countries'
country = Column(db.String(50), nullable=False)
last_update = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow)
def __repr__(self):
"""Represent instance as a unique string."""
return '<Country ({country})>'.format(country=self.country)
我的想法是,我只会创建一个城市,然后尝试将其添加到国家/地区。我想知道是否有更好的方法。