加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails:在单个功能测试中多次获取请求

发布时间:2020-12-17 03:54:40 所属栏目:百科 来源:网络整理
导读:我想在相同的测试中对一些获取请求进行分组,但是我得到了不稳定的行为.我有以下两个测试: test 'index for local seller (same site)' do seller = FactoryGirl.create :seller,business_site: @open_or.business_site get :index,nil,{user_id: seller.to_
我想在相同的测试中对一些获取请求进行分组,但是我得到了不稳定的行为.我有以下两个测试:

test 'index for local seller (same site)' do
  seller = FactoryGirl.create :seller,business_site: @open_or.business_site
  get :index,nil,{user_id: seller.to_param }
  assert_select "table#order_requests tr##{@controller.view_context.dom_id @open_or}"
end
test 'index for local seller (different site)' do
  seller = FactoryGirl.create :seller_local
  get :index,{user_id: seller.to_param }
  assert_select "table#order_requests tr##{@controller.view_context.dom_id @open_or}",false
end

我希望在一个测试下合并,但如果我这样做,第二个断言将错误地失败(预期正好0个元素匹配“table#order_requests tr#order_request_1000244799”,找到1.).我真的不明白为什么?第二次’get’调用可能无法正常重置某些内容.我想方设法“重置”请求但没有成功.

相关:making two requests to the same controller in rails integrations specs

解决方法

我在功能测试中注意到的一个重要区别(与集成相反)是控制器的状态似乎不会在请求之间重置,这可能导致意外结果.例如,考虑这个(人为的)控制器:

class ThingyController < ApplicationController
  def one 
    @thingy = Thingy.first
    render :nothing => true
  end 

  def two 
    render :nothing => true
  end 
end

行动’一’设置@ thingy,而动作’一’设置不行.但是,此功能测试失败:

test "thingy should not exist in second request" do
  get :one
  assert_not_nil assigns(:thingy),"thingy should exist in get_one"
  get :two
  assert_nil assigns(:thingy),"thingy should be absent in get_two"
end

据推测,这是因为第一个请求中的@thingy在测试方法的持续时间内仍然作为控制器中的实例变量.

虽然你可以在一次测试中进行多次get / put / etc调用,但我认为它们不是为每个测试方法测试多个动作而设计的.按Rails API TestCase docs:

Functional tests allow you to test a single controller action per test
method. This should not be confused with integration tests (see
ActionDispatch::IntegrationTest),which are more like “stories” that
can involve multiple controllers and multiple actions (i.e. multiple
different HTTP requests).

如果您真的希望将这两个操作结合起来,那么集成测试可能是更好的方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读