Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Rspec 在块之前运行代码_Rspec - Fatal编程技术网

Rspec 在块之前运行代码

Rspec 在块之前运行代码,rspec,Rspec,而不是这样做: 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 expe

而不是这样做:

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
我希望能够做到这一点:

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
为此,我必须创建一个自定义匹配器:

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
就像我说的,我需要做的就是跑步:

number_before = count_records
在before块之前

  before do
    post :create, asset: { parent_id: nil, uploaded_file: file }
  end

他跑了。这可能吗?有什么想法吗?rspec是否提供了任何钩子?

我不知道如何实现您所要求的,但下面确实减少了一些重复

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

使用时间状态,添加额外变量

time_b=0 
 do
 number_before = count_records
time_b!=0
do 
  number_after = countrecords
 before do
post :create, asset: { parent_id: nil, uploaded_file: file }
 end

这应该可以解决问题。

嗨,彼得。我已经投了更高的票,但没有接受,因为我想悬赏。如果没有人回应悬赏,我会再次接受。希望你不介意!