1
他们说完美的测试只包括测试框架和被测试的类;其他一切应该被嘲笑。那么,关联呢?如何编写rails关联的规范?
我并不是指简单的has_many
,belongs_to
关联,但关联扩展和范围。我真的很想写范围的规格,但我不知道如何去做。
他们说完美的测试只包括测试框架和被测试的类;其他一切应该被嘲笑。那么,关联呢?如何编写rails关联的规范?
我并不是指简单的has_many
,belongs_to
关联,但关联扩展和范围。我真的很想写范围的规格,但我不知道如何去做。
我得到了这个赶上了。在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'的用法。 – mliebelt
我想补充一句,“测试你自己编写的代码。”如果你的模型类与关联做的唯一事情就是定义它,那么确保关联被定义就足够了(比如,通过确保你可以访问fixture上的has_many数组)。如果方法调用has_many#build,请测试您的方法,而不是has_many的#build功能。不要采取这种做法,“我的模型提供财产的保证'posts'可以做x,y,z,所以我必须测试它可以做x,y,z。这就是疯狂。选项组合可算作“你的代码”来测试imo –