0

我使用的是 Rails 版本 3.2.12,但我的集成测试存在一些问题(单元和功能测试运行良好)。

我使用以下命令创建集成测试:

rails generate integration_test user_stories

然后我填充了“user_stories_test.rb”文件,如下所示:

require 'test_helper'

class UserStoriesTest < ActionDispatch::IntegrationTest

  LineItem.delete_all
  Order.delete_all
  ruby_book = product(:ruby)

  get "/"
  assert_response :success
  assert_template "index"

  xml_http_request :post, '/line_items', product_id: ruby_book.id
  assert_response :success
  cart = Cart.find(session[:cart_id])
  assert_equal 1, cart.line_items.size
  assert_equal ruby_book, cart.line_items[0].product

  get "/orders/new"
  assert_response :success
  assert_template "new"

  post_via_redirect "/orders",
                    order: { name: "Dave Thomas",
                             address: "123 The Street",
                             email: "dave@example.com",
                             pay_type: "Check" }
  assert_response :success
  assert_template "index"
  cart = Cart.find(session[:cart_id])
  assert_equal 0, cart.line_items.size

  orders = Order.all
  assert_equal 1, orders.size
  order = orders[0]
  assert_equal "Dave Thomas", order.name
  assert_equal "123 The Street", order.address
  assert_equal "dave@example.com", order.email
  assert_equal "Check", order.pay_type
  assert_equal 1, order.line_items.size
  line_item = order.line_items[0]
  assert_equal ruby_book, line_item.product

  mail = ActionMailer::Base.deliveries.last
  assert_equal ["dave@example.com"], mail.to
  assert_equal 'Sam Ruby <depot@example.com>', mail[:from].value
  assert_equal "Pragmatic Store Order Confirmation", mail.subject

end

这就是我的“test_helber.rb”文件的样子:

ENV["RAILS_ENV"] = "test"
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'

class ActiveSupport::TestCase
  fixtures :all
end

首先,我的固定装置没有加载,在我无法按照这些说明修复此问题后,我已经结束手动创建测试数据,如下所示:

  #ruby_book = product(:ruby)

  ruby_book = Product.new
  ruby_book.title = 'Programming Ruby 2.0'
  ruby_book.price =  49.50
  ruby_book.image_url = 'ruby.png'
  ruby_book.description = 'description'
  ruby_book.save!

这解决了夹具加载的问题,现在我的“get”方法出现“方法未定义”错误。更重要的是,在我评论了所有“get”方法之后,我在下一个方法 - “xml_http_request”上遇到了同样的错误。

我做错了什么?为什么 rails 找不到这些方法?

4

1 回答 1

1

运行此代码时,您不在测试的上下文中。

Test::Unit 案例的格式如下:

require 'test_helper'

class UserStoriesTest < ActionDispatch::IntegrationTest
  def test_it_works_as_it_should  # <-- this is the part you're missing!
    # Your test code goes here
  end
end

仅将测试代码放在一个类中并不能完成 Test::Unit 期望测试正确运行的所有正确设置。

有关在 Rails 中进行测试的更多信息:http: //guides.rubyonrails.org/testing.html#integration-testing

于 2013-03-10T09:20:08.060 回答