Search code examples
rubyrspec-rails

Rspec yield in let helper


As in the title. Is there possibility to yield something to 'let'? Like here:

let(:call_request) { post :create, article: FactoryGirl.attributes_for(yield) }

When I'm trying to use it:

it 'creates a new article' do
  expect { call_request { :article } }.to change(Article, :count).by(1)
end

It says:

ArticlesController POST create when admin signed in with valid attributes creates a new article
     Failure/Error: let(:call_request) { post :create, article: FactoryGirl.attributes_for(yield) }

     LocalJumpError:
       no block given (yield)
     # ./spec/controllers/articles_controller_spec.rb:61:in `block (3 levels) in <top (required)>'

Can I somehow do that? Maybe syntax is wrong or there is smarter way to do so?


Solution

  • Just define a method:

    def call_request
      post :create, article: FactoryGirl.attributes_for(yield)
    end
    

    The only difference between let and a normal method is that let declarations are memoized per example. Since you intend to pass a block to it, the memoization isn't appropriate, anyway, and a method def will work better.