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?
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.
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 .
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With