B Seven
B Seven

Reputation: 45943

How to use let with multiple params in RSpec expectation?

  describe 'Spec' do
    let( :qux    ){ double 'qux' }
    let( :params ){ :foo, :bar, :baz }

    specify 'success' do
      qux.use :foo, :bar, :baz

      expect( qux ).to have_received( :use ).with params

This generates a syntax error because :foo, :bar, :baz is not valid Ruby.

What is a good way to do this?

Upvotes: 2

Views: 5727

Answers (3)

Arup Rakshit
Arup Rakshit

Reputation: 118271

In Rspec 3.0 or greater, you must need to write it as

require 'rspec'

RSpec.describe 'Spec' do
  let( :qux    ) { double 'qux' }
  let( :params ) { [:foo, :bar, :baz] }

  it 'success' do
    expect(qux).to receive(:use).with(*params)
    qux.use(*params)
  end
end

And when I'll run this test :-

Arup-iMac:arup_ruby$ rspec spec/test_spec.rb
.

Finished in 0.04997 seconds (files took 0.0904 seconds to load)
1 example, 0 failures

Upvotes: 1

ianks
ianks

Reputation: 1768

let(:var) { .. } is easy to misinterpret, but it's actually pretty simple. You are evaluating a Ruby block, and whatever is returned from the let Ruby block gets assigned to :var.

With that in mind, you need to return an actual Ruby object from the let block.

Try this:

let(:params) do
  [:foo, :bar, :baz]
end

Upvotes: 1

photoionized
photoionized

Reputation: 5232

Put the params in an array and use a splat if you want to do something like that. Also, since you're mocking qux you're going to have to stub out the use method:

RSpec.describe 'Spec' do
    let( :qux    ){ double 'qux' }
    let( :params ){ [:foo, :bar, :baz] }

    specify 'success' do
      qux.stub(:use)
      qux.use :foo, :bar, :baz
      expect( qux ).to have_received( :use ).with *params
    end
end

Upvotes: 3

Related Questions