How to pass argument to subject in rspec
Asked Answered
S

1

10

I have one subject block that I want to reuse in various places.

subject(:stubbed_data) do
  expect(response.body).to eq(dynamic_var)
end

The dynamic_var variable will be different for different test cases. Is there any way to call subbed_data subject with arguments so that I can have dynamic value for dynamic_var variable?

Sieber answered 13/3, 2018 at 7:43 Comment(0)
E
20

You're not supposed to pass arguments to subject. And, by the way, it's a wrong place to make assertions (things like expect), they need to be done inside it blocks. However, you can define (and redefine) your dependencies inside let blocks, like this:

class MyClass
  attr_reader :arg
  def initialize(arg)
    @arg = arg
  end
end

RSpec.describe MyClass do
  subject { MyClass.new(dynamic) }
  let(:dynamic) { 'default value' }

  context 'it works with default value' do
    it { expect(subject.arg).to eq 'default value' }
  end
  context 'it works with dynamic value' do
    let(:dynamic) { 'dynamic value' }
    it { expect(subject.arg).to eq 'dynamic value' }
  end
end
Ellary answered 13/3, 2018 at 8:19 Comment(1)
What if you're trying to test a class method that you can't initialize, and want to test many different inputs for?Glycoside

© 2022 - 2024 — McMap. All rights reserved.