【问题标题】:DRY controller specs with RSpec: repeated expect带有 RSpec 的 DRY 控制器规格:重复预期
【发布时间】:2015-03-06 22:23:29
【问题描述】:

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

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 规则建议使用“上下文”而不是“如果条件”。 好的,这是我的控制器规格:

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

正如我在上面所写的,我在多种情况下都有相同的重复“它应该”和相同的期望。如何“干燥”它?

【问题讨论】:

    标签: ruby-on-rails ruby rspec dry


    【解决方案1】:

    您想要一个共享示例: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-2 个条件,则行数相同。但是,如果您有大约 10 个条件和相同的测试,它会有所帮助。这正是我的情况。
    • PS 我的实际测试比这个演示示例大一点。
    • @bertbruynooghe 重点是表明共享示例组是保持 RSpec 测试 DRY 的方式。 DRY 与代码行无关。似乎最好保持 OP 的风格不变。
    【解决方案2】:

    其他的重复,主题代码和描述呢?

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

    【讨论】:

    • 这也是一个很好的例子。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-28
    • 1970-01-01
    相关资源
    最近更新 更多