ruby-on-rails - RSpec : repeated expect 的 DRY Controller 规范

标签 ruby-on-rails ruby rspec dry

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

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 规则建议使用“context”而不是“if condition”。 好的,这是我的 Controller 规范:

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

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

最佳答案

你想要一个共享的例子: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

关于ruby-on-rails - RSpec : repeated expect 的 DRY Controller 规范,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28887183/

相关文章:

ruby-on-rails - 使用 Actionmailer 接收电子邮件并阅读纯文本

jquery - Rails 3 表格远程不工作

ruby-on-rails - Cocoon添加关联,如何限制关联数

ruby - 适用于 Ruby 的 Azure SDK : Table Storage - query_entities page, 计数,跳过实体?

ruby-on-rails - RSpec:如何测试从 Controller 调用私有(private)辅助方法的辅助方法?

ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test

ruby-on-rails - 查找没有 id 的元素进行 Capybara 测试

javascript - Rails 在 HAML + Coffeescript 中使用数组

ruby-on-rails - 在 Spree 中覆盖 Controller - 自动加载常量时检测到循环依赖

python - 在我的 heroku box(Rails 应用程序)上安装一个 python 库,特别是 pycurl