Ruby on rails Rails:如何编写模型中所有属性的测试
在具有以下模型的标准Rails 4.0.2应用程序中: 应用程序/模型/歌曲Ruby on rails Rails:如何编写模型中所有属性的测试,ruby-on-rails,unit-testing,Ruby On Rails,Unit Testing,在具有以下模型的标准Rails 4.0.2应用程序中: 应用程序/模型/歌曲 class Song < ... # title (string) # duration (integer) # artist (string) # ... imagine a lot more attributes end 你试过使用断言吗 test "song attributes must not be empty" do song = Song.new assert song.inval
class Song < ...
# title (string)
# duration (integer)
# artist (string)
# ... imagine a lot more attributes
end
你试过使用断言吗
test "song attributes must not be empty" do
song = Song.new
assert song.invalid?
assert song.errors[:title].any?
assert song.errors[:duration].any?
end
因为您对属性有需求,所以需要验证 既然您有验证,测试验证就足够了。不需要在一个测试中检查所有属性,这将不会得到有意义的东西,并且会重复 更好的方法是分别测试每个验证。像
class Song < ActiveRecord::Base
validate :title, presence: true
end
test "title must not be blank" do
song = Song.new(title: '')
assert song.invalid?
end
classsong
通常我不会测试Rails已经做过的那些非常基本的事情。我将只测试一些至少有点定制的东西。无论如何,这取决于您的风格。我唯一的问题是:一行或两行代码
验证:属性,:存在…
现在生成大量测试代码。这个比例相差太远了……这就是为什么我认为有一种“rails”方式。不过,我喜欢你的推理,并将尝试它。(我要等几个小时,才能把你的答案标记为正确,以防有人想出更好的答案)@sytycs,我理解你的担心:)你也可以查看shoulda
gem,它会处理那些肮脏的工作。在我的记忆中,它是用于Rspec的,不确定mini test是否可以使用它。
class Song < ActiveRecord::Base
validate :title, presence: true
end
test "title must not be blank" do
song = Song.new(title: '')
assert song.invalid?
end