使用 lambda 测试 Rails 中的回调?
我有一个基于 Redis 的新闻提要,当某些事件发生时,它会通过回调将项目插入其中。例如,当用户在一本书上做笔记时,它会被插入到该书读者的新闻源中。
class Note < ActiveRecord::Base
after_save do |note|
notify_the note.book.readers
end
...
end
现在这很好,我 99% 确定它有效,因为我可以查看我的提要并看到那里的注释。我的问题是使用最新的 rspec-rails 在 Rails 3 上进行测试。
由于某种原因,这通过了:
spec/models/note_spec.rb
describe "note creation" do
it "should notify the readers of the book the note is on" do
@user.feed.count.should == 0
@note.save!
@user.feed.count.should == 1
end
end
但这没有:
spec/models/note_spec.rb
describe "note creation" do
it "should notify the readers of the book the note is on" do
lambda do
@note.save!
end.should change(@user.feed, :count).by(1)
end
end
我不明白有什么区别?
I have a redis based news feed which gets items inserted into it via callbacks when certain events happen. For example, when a user makes a note on a book, it is inserted into the news feeds of the readers of the book.
class Note < ActiveRecord::Base
after_save do |note|
notify_the note.book.readers
end
...
end
Now this is fine and I'm 99% sure it works since I can look at my feed and see the notes there. My problem is with testing it on Rails 3 with the latest rspec-rails.
For some reason this passes:
spec/models/note_spec.rb
describe "note creation" do
it "should notify the readers of the book the note is on" do
@user.feed.count.should == 0
@note.save!
@user.feed.count.should == 1
end
end
But this doesn't:
spec/models/note_spec.rb
describe "note creation" do
it "should notify the readers of the book the note is on" do
lambda do
@note.save!
end.should change(@user.feed, :count).by(1)
end
end
and I can't figure out what the difference is?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
RSpec 不支持此匹配器的 do/end 语法。请参阅本页底部的警告... http://apidock.com/rspec/Spec /匹配器/更改
RSpec doesn't support the do/end syntax for this matcher. See the warning at the bottom of this page... http://apidock.com/rspec/Spec/Matchers/change
为了使用 lambda 并测试更改,您需要使用大括号 {} —— do/end 语法尚不支持。
In order to use lambda and test for a change, you need to use curly brackets {} -- the do/end syntax is not supported (yet).