[英]testing queries using rspec and factory_girl : Is there a better way?
我有以下课程和关系
City has_many Cinemas
Cinemas has_many Movies
Movies has_many Ratings
Movies Has_many Genres through GenreMovie
我想测试查询
* Show me the all movies in NewYork
* Show me the all movies in NewYork order by the rating
* Show me the all movies in NewYork order by length_of_movie, in genre "Action"
* show me all movies in Cinema "X" order by rating, that are in Genre "SciFi"
目前,我的工作方式如下:使用Factory Girl,并将一堆模型链接在一起以进行数据检查,
city = create(:city)
cinema = create(:cinema, city: city)
5.times do
movie = create(:movie, cinema: cinema, tags: ["sci fi", "action"]
3.times do
create(:rating, score: 2.3, movie: movie)
end
end
并重复3-4生成足以查询的数据,但似乎很笨拙。
有没有更好的办法 ?
我通常使用非常“简约”的方法对此进行测试:
例如,对于您的第一种情况,我将制作两部电影,一部在纽约,一部在外面。 您的方法应该只在纽约返回一个
对于第二部影片,制作三部在纽约都具有不同评级的电影。 以非逻辑方式创建它们,以便无论如何对它们进行排序。 检查您的方法是否以正确的顺序返回它们
其他情况类似。
我不只是创作5x3电影。 毫无意义,只花时间...
您可以使用几种factory_girl构造来清理它们。 create_list
将创建一个对象数组,清理x.times do
块。 movie
工厂的with_ratings
特性可以允许您选择创建电影时自动创建评级(通过FactoryGirl回调)。 您甚至可以使用过渡属性来控制数量和等级。 因此,您的结果可能如下所示:
cinema = create(:cinema)
movies = create_list(
:movie,
5,
:with_ratings,
cinema: cinema,
tags: [...],
ratings_count: 3,
ratings_value: 2.3
)
如果您需要访问城市,可以通过cinema.city
获取。
看到:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.