RSPR的DRY控制器规格:重复预期

时间:2015-03-05 20:32:58

标签: ruby-on-rails ruby rspec dry

我的控制器规格中有很多条件和相同的期望:

if condition 1 - expect(reponse).to redirect_to same_url
if condition 2 - expect(reponse).to redirect_to same_url
if condition 3 - expect(reponse).to redirect_to same_url

RSpec的DRY规则建议使用“上下文”而不是“if condition”。 好的,有我的控制器规格:

RSpec.describe MyController, type: :controller do
  describe ".method" do
    context "when wrong hash" do
      it "redirect to error_url" do
        get :method, key: '123', hash: 'wrong_hash'
        expect(subject).to redirect_to error_url
      end
    end
    context "when status is blocked" do
      it "redirect to error_url" do
        get :method, key: '123', hash: valid_hash, status: 'blocked'
        expect(subject).to redirect_to error_url
      end
    end
    context "when status is expired" do
      it "redirect to error_url" do
        get :method, key: '123', hash: valid_hash, status: 'expired'
        expect(subject).to redirect_to error_url
      end
    end
  end
end

正如我上面写的那样,我有同样的重复“它应该”和多种条件下的相同期望。如何“干”呢?

2 个答案:

答案 0 :(得分:4)

您需要一个共享示例:http://www.relishapp.com/rspec/rspec-core/docs/example-groups/shared-examples

RSpec.describe MyController, type: :controller do
  shared_examples "redirects to error_url" do
    it "redirect to error_url" do
      get(:method, path_options)
      expect(subject).to redirect_to error_url
    end
  end

  describe ".method" do
    context "when wrong hash" do
      let(:path_options) { {key: '123', hash: 'wrong_hash'} }
      it_behaves_like "redirects to error_url"
    end
    # ...etc
  end
end

答案 1 :(得分:1)

其他重复,主题代码和说明怎么样?

describe '.method'  
  it{expect{get :method, key: correct_key, hash: wrong_hash}.to redirect_to error_url}  
  ...
end