Class: RubyReactor::RSpec::TestSubject

Inherits:
Object
  • Object
show all
Includes:
RSpec::Mocks::ExampleMethods
Defined in:
lib/ruby_reactor/rspec/test_subject.rb

Overview

rubocop:disable Metrics/ClassLength

Defined Under Namespace

Classes: StepProxy

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(reactor_class:, inputs:, context: {}, async: nil, process_jobs: true) ⇒ TestSubject

Returns a new instance of TestSubject.



11
12
13
14
15
16
17
18
19
# File 'lib/ruby_reactor/rspec/test_subject.rb', line 11

def initialize(reactor_class:, inputs:, context: {}, async: nil, process_jobs: true)
  @reactor_class = reactor_class
  @inputs = inputs
  @context_data = context
  @async = async
  @process_jobs = process_jobs
  @interceptors = []
  @executed = false
end

Instance Attribute Details

#reactor_instanceObject (readonly)

Returns the value of attribute reactor_instance.



9
10
11
# File 'lib/ruby_reactor/rspec/test_subject.rb', line 9

def reactor_instance
  @reactor_instance
end

#run_resultObject (readonly)

Returns the value of attribute run_result.



9
10
11
# File 'lib/ruby_reactor/rspec/test_subject.rb', line 9

def run_result
  @run_result
end

Instance Method Details

#composed(step_name) ⇒ Object Also known as: compose

Fluent API for mocking nested compose steps

Examples:

reactor.compose(:my_sub_reactor).mock_step(:inner_step) { ... }


61
62
63
64
65
66
67
# File 'lib/ruby_reactor/rspec/test_subject.rb', line 61

def composed(step_name)
  # If already executed, return the traversed subject
  return traverse_composed(step_name) if @executed

  # Otherwise return a configuration proxy
  StepProxy.new(self, step_name)
end

#current_stepSymbol?

Get the current step where the reactor is paused (interrupt step) Note: When multiple interrupts are ready, this returns just one of them. Use ‘ready_interrupt_steps` to get all ready interrupt steps.

Returns:

  • (Symbol, nil)

    the name of the current interrupt step, or nil if not paused



297
298
299
300
301
# File 'lib/ruby_reactor/rspec/test_subject.rb', line 297

def current_step
  ensure_executed!
  step = @reactor_instance.context.current_step
  step&.to_sym
end

#ensure_executed!Object



408
409
410
411
412
413
414
415
# File 'lib/ruby_reactor/rspec/test_subject.rb', line 408

def ensure_executed!
  run unless @executed

  # Process jobs if status is running and processing is enabled
  return unless @process_jobs && @reactor_instance.context.status.to_s == "running"

  process_pending_jobs
end

#errorObject



403
404
405
406
# File 'lib/ruby_reactor/rspec/test_subject.rb', line 403

def error
  res = result
  res.respond_to?(:error) ? res.error : nil
end

#failing_at(step_name, *nested_steps, element_index: nil, &block) ⇒ Object

— Configuration DSL —



23
24
25
26
27
28
29
30
# File 'lib/ruby_reactor/rspec/test_subject.rb', line 23

def failing_at(step_name, *nested_steps, element_index: nil, &block)
  @interceptors << {
    type: :failure,
    step_path: [step_name, *nested_steps],
    conditions: { element_index: element_index, block: block }
  }
  self
end

#failure?Boolean

Returns:

  • (Boolean)


277
278
279
280
# File 'lib/ruby_reactor/rspec/test_subject.rb', line 277

def failure?
  ensure_executed!
  @reactor_instance.context.status.to_s == "failed"
end

#map(step_name) ⇒ Object

Fluent API for mocking nested map steps

Examples:

reactor.map(:my_map).mock_step(:inner_step) { ... }


54
55
56
# File 'lib/ruby_reactor/rspec/test_subject.rb', line 54

def map(step_name)
  StepProxy.new(self, step_name)
end

#map_element(step_name, index: 0) ⇒ Object



128
129
130
131
# File 'lib/ruby_reactor/rspec/test_subject.rb', line 128

def map_element(step_name, index: 0)
  elements = map_elements(step_name)
  elements[index]
end

#map_elements(step_name) ⇒ Object

— Traversal —



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/ruby_reactor/rspec/test_subject.rb', line 94

def map_elements(step_name)
  ensure_executed!

  # Check composed_contexts
  entry = @reactor_instance.context.composed_contexts[step_name] ||
          @reactor_instance.context.composed_contexts[step_name.to_s] ||
          @reactor_instance.context.composed_contexts[step_name.to_sym]

  return [] unless entry && entry[:type] == :map_ref

  map_id = entry[:map_id]
  storage = RubyReactor.configuration.storage_adapter

  # This requires the storage adapter to implement retrieval of map element context IDs
  # If it's not implemented in MemoryAdapter (if used), we might need to fallback?
  # But tests use Redis.
  child_ids = storage.retrieve_map_element_context_ids(map_id, @reactor_instance.class.name)

  child_ids.map do |id|
    klass = RubyReactor::Context.resolve_reactor_class(entry[:element_reactor_class])
    child_instance = klass.find(id)
    self.class.new(
      reactor_class: child_instance.class,
      inputs: child_instance.context.inputs,
      context: child_instance.context,
      async: @async,
      process_jobs: @process_jobs
    ).tap do |s|
      s.instance_variable_set(:@executed, true)
      s.instance_variable_set(:@reactor_instance, child_instance)
    end
  end
end

#mock_step(step_name, *nested_steps, element_index: nil) {|args, context, original_impl| ... } ⇒ Object

Intercept a step and provide a custom implementation

Parameters:

  • step_name (Symbol, String)

    The name of the step to intercept

  • nested_steps (Array<Symbol, String>)

    Path to nested steps if applicable

  • element_index (Integer) (defaults to: nil)

    Optional index for map steps

Yields:

  • (args, context, original_impl)

    block to execute @yieldparam args [Hash] The arguments passed to the step @yieldparam context [RubyReactor::Context] The execution context @yieldparam original_impl [Proc] A proc that can be called to execute the original implementation:

    original_impl.call(args, context)
    


42
43
44
45
46
47
48
49
# File 'lib/ruby_reactor/rspec/test_subject.rb', line 42

def mock_step(step_name, *nested_steps, element_index: nil, &block)
  @interceptors << {
    type: :mock,
    step_path: [step_name, *nested_steps],
    conditions: { element_index: element_index, block: block }
  }
  self
end

#paused?Boolean

Check if the reactor is paused at an interrupt

Returns:

  • (Boolean)

    true if the reactor is in paused state



287
288
289
290
# File 'lib/ruby_reactor/rspec/test_subject.rb', line 287

def paused?
  ensure_executed!
  @reactor_instance.context.status.to_s == "paused"
end

#ready_interrupt_stepsArray<Symbol>

Get all ready interrupt steps (steps that can be resumed) This is useful when multiple interrupts are waiting concurrently.

Returns:

  • (Array<Symbol>)

    list of ready interrupt step names



307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
# File 'lib/ruby_reactor/rspec/test_subject.rb', line 307

def ready_interrupt_steps
  ensure_executed!
  return [] unless paused?

  # Build the dependency graph and get ready steps
  graph = RubyReactor::DependencyGraph.new
  graph_manager = RubyReactor::Executor::GraphManager.new(
    @reactor_class, graph, @reactor_instance.context
  )
  graph_manager.build_and_validate!
  graph_manager.mark_completed_steps_from_context

  # Filter to only interrupt steps (using interrupt? predicate method)
  ready = graph_manager.dependency_graph.ready_steps
  ready.select { |step_config| step_config.respond_to?(:interrupt?) && step_config.interrupt? }
       .map { |step_config| step_config.name.to_sym }
end

#resultObject

— Introspection (Auto-Run) —



223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/ruby_reactor/rspec/test_subject.rb', line 223

def result
  ensure_executed!

  ctx = @reactor_instance.context
  status = ctx.status.to_s
  case status
  when "failed"
    return ctx.failure_reason if ctx.failure_reason.is_a?(RubyReactor::Failure)

    RubyReactor::Failure.new(ctx.failure_reason || {})
  when "completed"
    # Determine the success value
    val = if @reactor_class.return_step
            ctx.intermediate_results[@reactor_class.return_step.to_sym]
          else
            # Return result of the last executed step
            # Execution trace contains: { step: name, ... }
            # Trace does not strictly contain result, so we look up in intermediate_results
            last_trace = ctx.execution_trace.last
            if last_trace
              step_name = last_trace[:step]
              # Handle symbol/string mismatch
              ctx.intermediate_results[step_name.to_sym] || ctx.intermediate_results[step_name.to_s]
            end
          end
    RubyReactor::Success.new(val)
  when "running"
    # Try to determine if it is truly running or if we just missed the completion
    if @process_jobs && defined?(Sidekiq::Testing)
      # Force one more check
      process_pending_jobs
      # Reload status
      @reactor_instance = @reactor_class.find(@reactor_instance.context.context_id)
      return result unless @reactor_instance.context.status.to_s == "running"
    end

    # If still running, return a Pending/Running result instead of nil
    # This allows matchers to report "expected success but was running"
    RubyReactor::Failure("Reactor is still running (Async operations pending?)",
                         retryable: true)
  when "paused"
    RubyReactor::InterruptResult.new(
      execution_id: ctx.context_id,
      intermediate_results: ctx.intermediate_results
      # We assume no error if paused normally
    )
  end
end

#resume(payload: {}, step: nil) ⇒ TestSubject

Resume a paused reactor with the given payload

Parameters:

  • payload (Hash) (defaults to: {})

    The data to provide to the interrupt step

  • step (Symbol, String, nil) (defaults to: nil)

    The specific interrupt step to resume. Required when multiple interrupts are ready. If not provided and only one interrupt is ready, that step will be used.

Returns:

  • (TestSubject)

    self for chaining and introspection

Raises:



333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
# File 'lib/ruby_reactor/rspec/test_subject.rb', line 333

def resume(payload: {}, step: nil)
  ensure_executed!

  unless paused?
    raise RubyReactor::Error::ValidationError,
          "Cannot resume: reactor is not paused (status: #{@reactor_instance.context.status})"
  end

  step_name = determine_resume_step(step)

  # Use the reactor's continue method
  @reactor_instance.continue(payload: payload, step_name: step_name)

  # Process any pending async jobs
  process_pending_jobs if @process_jobs && defined?(Sidekiq::Testing)

  # Reload the reactor instance to get updated state
  @reactor_instance = @reactor_class.find(@reactor_instance.context.context_id)

  # Return self for chaining and introspection
  self
end

#runObject

— Execution —



171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
# File 'lib/ruby_reactor/rspec/test_subject.rb', line 171

def run
  return self if @executed

  # 1. Apply Interceptors (Dynamic Subclassing)
  execution_class = prepare_execution_class

  # 2. Capture Context ID
  captured_context_id = nil

  allow(RubyReactor::Context).to receive(:new).and_wrap_original do |m, *args|
    ctx = m.call(*args)
    captured_context_id ||= ctx.context_id
    ctx
  end

  # 3. Native Run
  if @async == false
    allow(execution_class).to receive(:async?).and_return(false)
  elsif @async == true
    allow(execution_class).to receive(:async?).and_return(true)
  end

  @run_result = nil
  if @process_jobs && defined?(Sidekiq::Testing)
    # Ensure SidekiqAdapter is used to capture jobs in fake mode
    allow(RubyReactor.configuration).to receive(:async_router).and_return(RubyReactor::SidekiqAdapter)

    # Avoid nesting error which happens in Sidekiq 7+ if a mode is already set
    begin
      Sidekiq::Testing.fake! do
        @run_result = execution_class.run(@inputs)
      end
    rescue Sidekiq::Testing::TestModeAlreadySetError
      @run_result = execution_class.run(@inputs)
    end
  else
    @run_result = execution_class.run(@inputs)
  end

  # 4. Reload
  raise "Could not capture context ID during execution" unless captured_context_id

  # Reload using the execution class (which might be the mocked subclass with unique name)
  @reactor_instance = execution_class.find(captured_context_id)
  # Update our reference to the class so future reloads (e.g. in result introspection) work
  @reactor_class = execution_class
  @executed = true
  self
end

#run_async(boolean) ⇒ Object



164
165
166
167
# File 'lib/ruby_reactor/rspec/test_subject.rb', line 164

def run_async(boolean)
  @async = boolean
  self
end

#step_result(name) ⇒ Object



385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
# File 'lib/ruby_reactor/rspec/test_subject.rb', line 385

def step_result(name)
  ensure_executed!
  # Prefer intermediate_results as it is the data store
  # Logic to handle symbol vs string mismatch
  key_sym = name.to_sym
  key_str = name.to_s

  if @reactor_instance.context.intermediate_results.key?(key_sym)
    @reactor_instance.context.intermediate_results[key_sym]
  elsif @reactor_instance.context.intermediate_results.key?(key_str)
    @reactor_instance.context.intermediate_results[key_str]
  else
    # Fallback to execution trace if available (e.g. for inspection)
    entry = @reactor_instance.context.execution_trace.find { |t| t[:step].to_s == key_str }
    entry ? entry[:result] : nil
  end
end

#success?Boolean

Returns:

  • (Boolean)


272
273
274
275
# File 'lib/ruby_reactor/rspec/test_subject.rb', line 272

def success?
  ensure_executed!
  @reactor_instance.context.status.to_s == "completed"
end