Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass argument to subject in rspec

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?

like image 678
Sanjay Salunkhe Avatar asked Mar 13 '18 07:03

Sanjay Salunkhe


People also ask

What does subject mean in RSpec?

Summary: RSpec's subject is a special variable that refers to the object being tested. Expectations can be set on it implicitly, which supports one-line examples. It is clear to the reader in some idiomatic cases, but is otherwise hard to understand and should be avoided.

What is let in RSpec?

let generates a method whose return value is memoized after the first call. This is known as lazy loading because the value is not loaded into memory until the method is called. Here is an example of how let is used within an RSpec test. let will generate a method called thing which returns a new instance of Thing .

What is context in RSpec?

According to the rspec source code, “context” is just a alias method of “describe”, meaning that there is no functional difference between these two methods. However, there is a contextual difference that'll help to make your tests more understandable by using both of them.


1 Answers

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
like image 56
Alexey Shein Avatar answered Oct 21 '22 04:10

Alexey Shein