Rspec在let helper中产生

时间:2016-04-25 18:28:42

标签: ruby rspec-rails

如标题所示。是否有可能产生一些东西来让我们感到兴奋?像这里:

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

当我尝试使用它时:

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

它说:

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)>'

我能以某种方式这样做吗?也许语法错误或有更聪明的方法吗?

1 个答案:

答案 0 :(得分:1)

只需定义一个方法:

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

let和普通方法之间的唯一区别是每个示例都记录了let个声明。由于您打算将块传递给它,因此无论如何都不适用于memoization,并且def方法可以更好地工作。