我只是在学习 RoR,我在单元测试中遇到了一个问题,我写的一个简单的函数不会适当地修改它的对象。我一定错过了一些非常基本的东西,因为我在任何论坛上都看到过这个问题。
我通过“rake test test/functional/song_test.rb”使用 rake 运行我的测试。数据是从 yaml 文件加载的,这似乎是正确的。但是当我打电话给我的“投票!” 函数(见下文)修改属性@rating,更改在测试中不可见,我的断言失败。
test "vote!" do
song1 = songs(:song1) # 'songs' was loaded from a yaml file
assert song1.respond_to?('vote!'), "Can't vote!()!"
assert_equal 5, song1.rating, "Rating is wrong" # assertion passes
song1.vote!(1)
assert_equal 1, song1.rating, "Rating should be 1" # assertion fails
end
这是失败消息:
SongTest#test_vote! = 0.00 s
1) Failure:
test_vote!(SongTest) [/test/functional/song_test.rb:35]:
Rating should be 1.
<1> expected but was
<5>.
我用 puts() 验证了更改确实发生在投票中!功能。但是函数返回之后song1.rating 的值并没有改变。这是带投票的课程!功能。
class Song < ActiveRecord::Base
validates :rating, :presence => true
def vote!(num_stars)
@rating = num_stars
end
end
我在想,不知何故有两个对象副本和投票!函数在临时对象上调用。但我不明白这是怎么回事或为什么会这样。