ruby - 带线程的 Rspec

标签 ruby multithreading rspec

我有一个在初始化时启动线程的类,我可以通过公共(public)方法在该线程中推送一些操作:

class Engine

  def initialize
    @actions = []
    self.start_thread()
  end

  def push_action(action)
    start = @actions.empty?
    @actions.push(action)
    if start
      @thread.run
    end
  end

  protected

  def start_thread
    @thread = Thread.new do
      loop do

        if @actions.empty?
          Thread.stop
        end

        @actions.each do |act|
          # [...]
        end
        @actions.clear
        sleep 1
      end
    end
  end
end

我想用 RSpec 测试这个类来检查当我通过一些 Action 时会发生什么。但我不知道该怎么做。

提前致谢

最佳答案

好的,我找到了一个解决方案,但它很脏:

describe Engine do

  describe "#push_action play" do

    it "should do the play action" do
      # Construct the Engine with a mock thread
      mock_thread = double("Useless Thread")
      allow(mock_thread).to receive(:run)
      expect(Thread).to receive(:new).and_return(mock_thread)
      engine = Engine.new

      allow(engine).to receive(:sleep)

      # Expect that the actual play action will be processed
      expect(engine).to receive(:play)

      # push the action in the actions' list
      engine.push_action(:play)

      # Stop the thread loop when the stop() method is called
      expect(Thread).to receive(:stop).and_raise(StandardError)


      # Manually call again the start_thread() protected method with a yielded thread
      # in order to process the action
      expect(Thread).to receive(:new).and_yield
      expect {engine.send(:start_thread)}.to raise_error(StandardError)  
    end

  end
end

如果有人有更好的解决方案,我会很高兴:)

关于ruby - 带线程的 Rspec,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48585585/

相关文章:

ruby - 从 OS X 应用程序运行 ruby​​ 脚本

c# - 如果作为单独的任务启动,有没有办法取消 Parallel.ForEach 循环

multithreading - Kotlin 协程 : Waiting for multiple threads to finish

ruby - 在测试之间删除 Cassandra DB (Rspec)

ruby-on-rails - 使用 RSpec 测试 Redis 事务

python - 寻找关于网络抓取项目最佳实践的好教程的推荐?

ruby-on-rails - Ruby on Rails 和 XSS 预防

ruby-on-rails - 按距给定点的距离对位置进行排序,并按 mongoid 中的最大距离过滤结果

multithreading - 如何以线程安全的方式停止正在运行的任务?

ruby - 对 Ruby 中的 block 行为感到困惑