如何使用RSpec测试after_save回调中的类初始化?

时间:2012-09-17 17:26:08

标签: ruby-on-rails-3 testing rspec callback initialization

我有以下方法:

class Topic
def create_or_rename_folder
  unless self.destroyed?
    bucket = CreateTopicFolder.new(bucket_name)
    bucket.create_or_rename_folder(permalink.split("/").last)
  end
end
...

被称为:after_save :create_or_rename_folder, :if => :production_env?

我想测试一下,在创建新的Topic时,会创建一个新的CreateTopicFolder实例,而如果正在销毁Topic, <{1}}的新实例正在创建。

该课程类似于:

CreateTopicFolder

对此进行测试的正确方法是什么?

谢谢!

1 个答案:

答案 0 :(得分:0)

context "When creating a Topic" do
  it "creates a CreateTopicFolder" do
    create_topic_folder = mock(CreateTopicFolder)
    CreateTopicFolder.stub(:new) { create_topic_folder }
    create_topic_folder.
      should_receive(:create_or_rename_folder).
      with("Sample Bucket Name")
    topic = Topic.new
    topic.bucket_name = "Sample Bucket Name"
    topic.save!
  end
end

context "When destroying a Topic" do
  it "does not create a CreateTopicFolder" do
    CreateTopicFolder.should_not_receive(:new)
    topic = mock_model(Topic)
    topic.destroy
  end
end