使用 lambda 测试 Rails 中的回调?

发布于 2024-11-02 03:21:13 字数 819 浏览 1 评论 0原文

我有一个基于 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

永不分离 2024-11-09 03:21:13

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

爱要勇敢去追 2024-11-09 03:21:13

为了使用 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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文