使用 I18N 的基本设计规范 [英] Basic Devise spec with I18N

查看:24
本文介绍了使用 I18N 的基本设计规范的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 RSpec 的新手,正在尝试编写一个简单的测试来显示 Devise 正在工作.我随机选择了一个页面,想编写一个测试,显示未登录的用户被重定向到/users/sign_in.

I'm new to RSpec, and trying to write a simple test that shows Devise is working. I've picked a random page and want to write a test that shows that a non logged-in user is re-redirected to /users/sign_in.

describe OrgsController do

  describe "GET index when not logged in" do
    it "redirects to new_user_session_path" do
      user = FactoryGirl.create(:user)
      user.confirm!
      sign_in user
      sign_out user
      get :index
      response.should redirect_to new_user_session_path
    end
  end

  before(:each) do
    user = FactoryGirl.create(:user)
    user.confirm!
    sign_in user
  end

  # remaining specs

end

我收到 预期的响应是重定向到 但重定向到了 ."

我已经实现了 i18n,并且在我的应用程序控制器中有:

I have implemented i18n, and have in my Application Controller:

before_filter :set_i18n_locale_from_params

实现此功能的最佳方法是:

What is the best way to get this working in terms of:

  • 让路线匹配?
  • 为了避开 before(:each) 块的影响而让用户再次登录和退出的黑客行为?
  • 总体方法?

推荐答案

让控制器测试/规范正确设置区域设置的问题是一个长期存在的问题,请参阅:如何为功能测试(Rails)设置locale default_url_options

The problem of getting controller tests/specs to properly set the locale is a longstanding one, see: How to set locale default_url_options for functional tests (Rails)

从您所写的内容来看,get :index 默认没有设置语言环境,因为 default_url_options 在控制器测试/规范中不起作用.尝试上面链接中提到的解决方案之一,以使路由匹配.另请参阅 github 上的此讨论:https://github.com/rspec/rspec-rails/issues/255

From what you've written, it looks like get :index is not setting the locale by default, because default_url_options will not work from controller tests/specs. Try one of the solutions mentioned in the link above to get the routes to match. See also this discussion on github: https://github.com/rspec/rspec-rails/issues/255

就其价值而言,这是补丁我目前在规范/测试中使用以将区域设置自动传递到当前区域设置的路由:

For what it's worth, this is the patch I currently use in specs/tests to get the locale to be automatically passed to routes from the current locale:

class ActionDispatch::Routing::RouteSet
  def url_for_with_locale_fix(options)
    url_for_without_locale_fix(options.merge(:locale => I18n.locale))
  end

  alias_method_chain :url_for, :locale_fix
end

关于您拥有的 before(:each) 块设置的hackishness,我真的建议使用上下文块分离案例,一个上下文没有登录用户的 before 过滤器,并且另一个使用 before 块登录用户.您现在的设置对于试图了解正在发生的事情的人来说确实令人困惑.

Regarding the hackishness of the before(:each) block setup you have, I'd really suggest separating the cases using context blocks, with one context without the before filter logging the user in, and another with the before block logging the user in. The setup you have right now is really confusing for someone trying to see what's going on.

这篇关于使用 I18N 的基本设计规范的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆