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

ruby-on-rails – Rspec – 测试rails视图是否呈现特定的部分

发布时间:2020-12-17 03:31:48 所属栏目:百科 来源:网络整理
导读:我有一个运行rspec-rails 2.14.0的rails 3.2.13应用程序,我正在尝试确认视图在我的测试中呈现特定的部分.它确实有效,但我需要添加此测试.这是我到目前为止所拥有的: require 'spec_helper'describe 'users/items/index.html.haml' do let(:current_user) {
我有一个运行rspec-rails 2.14.0的rails 3.2.13应用程序,我正在尝试确认视图在我的测试中呈现特定的部分.它确实有效,但我需要添加此测试.这是我到目前为止所拥有的:

require 'spec_helper'

describe 'users/items/index.html.haml' do
  let(:current_user) { mock_model(User) }

  context 'when there are no items for this user' do
    items = nil

    it 'should render empty inventory partial' do
      response.should render_template(:partial => "_empty_inventory")
    end

  end
end

这运行没有错误,但没有通过.失败的是:

Failure/Error: response.should render_template(:partial => "_empty_inventory")
   expecting partial <"_empty_inventory"> but action rendered <[]>

谢谢你的任何想法.

编辑

这对我有用,但彼得的解决方案更好……

context 'when there are no items for this user' do

  before do
    view.stub(current_user: current_user)
    items = nil
    render
  end

  it 'should render empty inventory partial' do
    view.should render_template(:partial => "_empty_inventory")
  end

end

出于某种原因,我必须在视图上调用渲染,这是违反直觉的,但是你去…

解决方法

因此,通常测试特定部分是否在视图规范中呈现的方式是测试部分的实际内容.例如,假设您的_empty_inventory parial具有“没有库存”消息.然后你可能有一个像:

it "displays the empty inventory message" do
    render
    rendered.should_not have_content('There is no inventory')
  end

或者,您可以使用控制器规范,在这种情况下,您需要在设置规范时调用“render_views”方法.然后你可以做类似的事情

it 'should render empty inventory partial' do
  get :index,:user_id => user.id
  response.should render_template(:partial => "_empty_inventory")
end

假设您已为控制器规范设置状态.

(编辑:李大同)

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

    推荐文章
      热点阅读