gpt4 book ai didi

ruby - 带线程的 Rspec

转载 作者:太空宇宙 更新时间:2023-11-03 16:41:32 25 4
gpt4 key购买 nike

我有一个在初始化时启动线程的类,我可以通过公共(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com