在块之前运行代码 [英] Run code before before block
本文介绍了在块之前运行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
而不是这样做:
subject { response }
context 'when orphan' do
before do
post :create, asset: { parent_id: nil, uploaded_file: file }
end
it { should have_http_status 201 }
it { should redirect_to_location '/' }
it 'create a asset' do
expect { post :create, asset: { parent_id: nil, uploaded_file: file } }.to change(Asset, :count).by(1)
end
end
我希望能够做到这一点:
I want to be able to do this:
subject { response }
context 'when orphan' do
before do
post :create, asset: { parent_id: nil, uploaded_file: file }
end
it { should have_http_status 201 }
it { should redirect_to_location '/' }
it { should create_an(:asset) }
end
为此,我必须创建一个自定义匹配器:
To do this I'll have to create a custom matcher:
RSpec::Matchers.define :create_an do |instance|
match do |actual|
#### ALL I NEED IS A WAY TO TRIGGER THIS LINE
# BEFORE THE BEFORE BLOCK
# before_before do
number_before = count_records
# end
##############################################
number_after = count_records
number_after - number_before == 1
end
def count_records
instance.to_s.classify.constantize.count
end
failure_message_for_should do |actual|
"..."
end
failure_message_for_should_not do |actual|
"..."
end
description do
"should create an #{instance.to_s}"
end
end
就像我说的,我需要做的就是运行:
Like I say, all I need to do is run:
number_before = count_records
在before块之前,
before the before block,
before do
post :create, asset: { parent_id: nil, uploaded_file: file }
end
正在运行.这可能吗?有任何想法吗?rspec 是否为此提供了任何钩子?
is run. Is this possible? Any ideas? Any hooks rspec provides for this?
推荐答案
我不知道有什么方法可以实现您所要求的内容,但以下内容确实减少了一些重复.
I don't know of a way to implement what you've asked for, but the following does reduce some duplication.
context 'when orphan' do
let(:create) { post :create, asset: { parent_id: nil, uploaded_file: file } }
context 'the response' do
before { create }
subject { response }
it { is_expected.to have_http_status 201 }
it { is_expected.to redirect_to_location '/' }
end
it 'creates a asset' do
expect { create }.to change(Asset, :count).by(1)
end
end
这篇关于在块之前运行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文