【问题标题】:How to test a class initialization in after_save callback with RSpec?如何使用 RSpec 在 after_save 回调中测试类初始化?
【发布时间】:2012-09-17 17:26:07
【问题描述】:

我有以下方法:

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 被销毁,@987654326 的新实例@ 是没有被创建的。

那个类看起来像:

class CreateTopicFolder

   def initialize(bucket_name)
    s3 = AutoVideoAssociate
    s3.connect
    @bucket = s3.find_bucket(bucket_name)
  end
  ...

测试这个的正确方法是什么?

谢谢!

【问题讨论】:

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


    【解决方案1】:
    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-19
      • 1970-01-01
      • 2012-02-10
      • 2014-07-16
      • 1970-01-01
      • 2015-04-12
      • 2015-04-22
      相关资源
      最近更新 更多