开发者

How to test ActiveRecord callbacks with RSpec?

How to test the 开发者_StackOverflowfollowing example?

class Post < ActiveRecord::Base
  belongs_to :discussion, touch: true
end


You can set a message expectation:

it "should touch the discussion" do
  post = Factory.build(:post)
  post.discussion.should_receive(:touch)
  post.save!
end

This examples uses Factory Girl, but you could use fixtures or mocks as well.


Firstly

If all you're trying to do is assert that the touch: true option is set on your association, then you can just do the following:

describe Post do
  it { should belong_to(:discussion).touch(true) }
end

Secondly

For testing callbacks in general, read on.

All of the other answers here have two flaws:

  1. They require a hit on the database, which can be slow.

  2. They do not determine which callback is called during a save!

Instead, use the Shoulda Callback Matchers, which doesn't require a database hit and you can specify which callback you're testing the existence of.

Installation

Install the Shoulda Callback Matchers with Bundler:

group :test do
  gem "shoulda-callback-matchers", "~> 1.0"
end

Usage

it { should callback(:some_method).after(:save) }

Thank you to Beat for writing this great library.


You can mock the #touch call, or verify the effects of your callback on it.

it "should touch the discussion" do
  original_updated_at = @discussion.updated_at
  @post.save!
  @post.discussion.updated_at.should_not_be == original_updated_at
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜