【问题标题】:Including SessionsHelper in RailsTutorial.org test_helper: why not?在 RailsTutorial.org test_helper 中包含 SessionsHelper:为什么不呢?
【发布时间】:2016-04-13 10:05:09
【问题描述】:

railstutorial.orgListing 8.23

ENV['RAILS_ENV'] ||= 'test'
.
.
.
class ActiveSupport::TestCase
  fixtures :all

  # Returns true if a test user is logged in.
  def is_logged_in?
    !session[:user_id].nil?
  end
end

建议创建一个重复的方法来检查当前用户是否登录(已经在sessions_helper.rb 中定义了这样的方法)用于测试。但是,我想知道为什么作者首先选择这样做。他这样解释他的推理:

要测试Listing 8.22 的行为,我们可以在Listing 7.26 的测试中添加一行以检查用户是否已登录。在这种情况下定义 is_logged_in 会很有帮助?辅助方法来并行logged_in?在Listing 8.15 中定义的helper,如果(测试)会话中有用户ID,则返回true,否则返回false(Listing 8.23)。 (因为辅助方法在测试中不可用,我们不能像Listing 8.15那样使用current_user,但是会话方法是可用的,所以我们使用它。)这里我们使用is_logged_in?而不是logged_in?这样 test helper 和 Sessions helper 方法就有不同的名字,这样就不会被误认为是彼此了。

但是,在第 5 章的练习中,作者在其测试套件中编写了包含ApplicationHelper 的代码(请参阅Listing 5.37):

ENV['RAILS_ENV'] ||= 'test'
.
.
.
class ActiveSupport::TestCase
  fixtures :all
  include ApplicationHelper
  .
  .
  .
end

当我包含SessionsHelper 并使用该帮助模块中的代码运行我的测试时,我的测试仍然通过。我想知道作者是否选择放弃在代码中包含 SessionsHelper 是因为该技术已在练习中使用(因此最好在其他地方应用),或者实际上是否出于某种原因将 SessionsHelper 包含到测试套件中是一件坏事或其他。对此有何见解?

【问题讨论】:

    标签: ruby-on-rails ruby testing railstutorial.org helpers


    【解决方案1】:

    读完第 8 章后,我发现使用 logged_in? 的代码(即 !current_user.nil?)测试用户是否登录在某种程度上无法用于测试,因此方法 current_user 不起作用t 实际上工作(即,它总是以某种方式返回true)。虽然我不知道究竟是为什么;我基于这句话:

    (因为辅助方法在测试中不可用,我们不能像清单 8.15 那样使用 current_user,但是 session 方法是可用的,所以我们使用它来代替。)

    所以基本上在测试中使用current_user 方法是行不通的,因为它在测试中不可用? (不过,我以为我将它们包含在 test_helper.rb 中,并带有 include SessionsHelper 行。

    这是我现在的答案。如果比我更博学的人能证实其内部运作,那就太好了。

    编辑:好的,我认为这是因为 current_user 方法使用 @current_user ||= User.find_by(id: user_id)User 数据库在开发和测试之间是不同的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-12
      • 2014-04-12
      • 2011-07-26
      • 2015-04-25
      相关资源
      最近更新 更多