【发布时间】:2011-11-18 21:43:19
【问题描述】:
他们说完美的测试只包括测试框架和被测试的类;其他一切都应该被嘲笑。那么,联想呢?
我指的不是简单的has_many、belongs_to 关联,而是关联扩展和范围。我真的很想为范围编写规范,但我就是不知道该怎么做。
【问题讨论】:
标签: ruby-on-rails-3 rspec associations scopes
他们说完美的测试只包括测试框架和被测试的类;其他一切都应该被嘲笑。那么,联想呢?
我指的不是简单的has_many、belongs_to 关联,而是关联扩展和范围。我真的很想为范围编写规范,但我就是不知道该怎么做。
【问题讨论】:
标签: ruby-on-rails-3 rspec associations scopes
我也对此感到困惑。在 Rspec 中,他们摆脱了“单元测试”的想法。在实践中,Rails 中的单元测试至少对我来说意味着测试模型上的属性值。但你是对的,联想呢?
在 Rspec 中,您只需创建一个 spec/models 目录,然后测试您的模型。在模型规范 (spec/models/user_spec.rb) 的顶部,您进行了单元测试(测试您的属性),然后您在下面测试每个关联:
require 'spec_helper'
describe User do
context ":name" do
it "should have a first name"
it "should have a last name"
end
# all tests related to the gender attribute
context ":gender" do
it "should validate gender"
end
# all tests related to "belongs_to :location"
context ":location" do
it "should :belong_to a location"
it "should validate the location"
end
# all tests related to "has_many :posts"
context ":posts" do
it "should be able to create a post"
it "should be able to create several posts"
it "should be able to list most recent posts"
end
end
但是现在您在User 测试中测试Post 和Location 模型?是的。但是Post 模型除了与用户相关的功能之外,还有很多额外的东西。与Location 相同。所以你会有一个spec/models/location_spec.rb 喜欢:
require 'spec_helper'
describe Location do
context ":city" do
it "should have a valid city"
end
context ":geo" do
it "should validate geo coordinates"
end
end
在我看来,这些都不应该被嘲笑。在某些时候,您必须实际测试关联是否正在保存并且可查询。就在这里。想想看,在模型规范中,你有属性的“单元测试”和关联的“集成测试”。
【讨论】:
ActiveRecord 有效,只测试您对ActiveRecord 的使用是否有效。
posts可以做x、y、z,所以我必须测试它可以做x、y、z。那样是疯狂的。注意具体选项组合算作测试 imo 的“您的代码”