【问题标题】:How to set up RSpec to use locale by default in Ruby On Rails如何在 Ruby On Rails 中设置 RSpec 以默认使用语言环境
【发布时间】:2021-01-19 13:10:16
【问题描述】:

我有一个新近启动的 Rails 应用程序,并且我也使用 Rspec 构建了该项目,因此它生成了大量测试。但是spec/routing 文件夹中的所有这些测试都失败了。 这是我的my_models_routing_spec.rb 文件:

RSpec.describe MyModelController, type: :routing do
  describe "routing" do
    it "routes to #index" do
      expect(get: "/my_models").to route_to("my_models#index")
    end
  end
end

这是错误信息:

1) MyModelController routing routes to #index
     Failure/Error: expect(get: "/my_model").to route_to("my_model#index")
       No route matches "/my_model"
     # ./spec/routing/my_model_routing_spec.rb:6:in `block (3 levels) in <main>'

我认为这是因为我的路线被限定在语言环境中:

Rails.application.routes.draw do
  scope "/:locale", locale: /#{I18n.available_locales.join("|")}/ do
    root to: "home#index"
    resources :my_models
  end
  get "/*path", to: redirect("/#{I18n.default_locale}/%{path}", status: 302),
                constraints: { path: /(?!(#{I18n.available_locales.join("|")})\/).*/ },
                format: false

end

这是所有测试的情况。有没有办法配置 Rspec 以考虑语言环境?提前致谢。

【问题讨论】:

    标签: ruby-on-rails rspec


    【解决方案1】:

    如果您真的想测试您的路线,那么为什么不使用所有可用的语言环境对其进行测试呢? 像这样的:

    RSpec.describe MyModelController, type: :routing do
      describe "routing" do
        it "routes to #index" do
          I18n.availble_locals.each do |locale|
            expect(get: "#{locale}/my_models").to route_to("my_models#index")
          end
        end
      end
    end
    

    或者你可以像这样测试路径:

    RSpec.describe MyModelController, type: :routing do
      describe "routing" do
        it "routes to #index" do
          expect(get: my_models_path).to route_to("my_models#index")
        end
      end
    end
    

    【讨论】:

      【解决方案2】:

      查看@Hacman 的代码,我找到了解决方案。我发布了对我有用的版本。感谢哈克曼。

      RSpec.describe MyModelController, type: :routing do
        describe "routing" do
          I18n.available_locales.each do |locale|
            it "routes to #index" do
              expect(get: "#{locale}/my_model", ).to route_to("my_model#index", locale: "#{locale}")
            end
          end
        end
      end
      
      

      【讨论】:

        猜你喜欢
        • 2014-09-14
        • 2012-07-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-07
        • 2012-02-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多