【问题标题】:make a helper for my methods for integration testing in rails 3为我在 rails 3 中进行集成测试的方法提供帮助
【发布时间】:2014-08-15 09:36:01
【问题描述】:

我正在为我的 rails 3.2.16 应用程序准备一些集成测试,我认为在我的用户场景中,我有几个调用会在许多测试中重复,所以我想通过放置它们来干燥它们在单独的公共模块中,

例如我创建了/test/integration/my_test_helpers.rb

require 'test_helper'

module MyTestHelper

  def login_user(email, password, stay = 0)
    login_data = {
      email: email,
      password: password,
      remember_me: stay
    }
    post "/users/sign_in", user: login_data
    assert_redirected_to :user_root
  end
end

并尝试在我的集成测试中使用它:

require 'test_helper'
require "./my_test_helpers.rb"

class CreateCommentTest < ActionDispatch::IntegrationTest

  setup do
    @user = users(:user1)
  end

  test "create comment" do
    login_user @user.email, "password", 1
  end
end

我得到异常:

`require': cannot load such file -- ./my_test_helpers.rb (LoadError)

如何加载模块?把MyTestHelpers做成一个模块对吗?

【问题讨论】:

    标签: ruby-on-rails ruby testing integration-testing


    【解决方案1】:

    你应该把你的助手放在支持文件夹(test/support/my_test_helpers.rb,或其他东西)并在test_helper.rb中加载模块:

    ENV["RAILS_ENV"] ||= "test"
    require File.expand_path("../../config/environment", __FILE__)
    require "rails/test_help"
    
    require_relative "./support/my_test_helpers"
    
    require "minitest/rails"
    
    class ActiveSupport::TestCase
      ActiveRecord::Migration.check_pending!
    
      fixtures :all
    
      # Add more helper methods to be used by all tests here...
    end
    

    不记得include你的模块:

    require 'test_helper'
    
    class CreateCommentTest < ActionDispatch::IntegrationTest
      include MyTestHelper
    
      setup do
        @user = users(:user1)
      end
    
      test "create comment" do
        login_user @user.email, "password", 1
      end
    end
    

    【讨论】:

    • 谢谢,现在好多了,虽然我还有undefined method login_user'`
    猜你喜欢
    • 2014-01-13
    • 2015-10-11
    • 1970-01-01
    • 1970-01-01
    • 2013-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-27
    相关资源
    最近更新 更多