【问题标题】:Rspec: test not passing when it shouldRspec:测试不应该通过
【发布时间】:2014-05-02 02:20:09
【问题描述】:

这里的第二个测试通过了,第一个没有。不知道为什么。

require 'spec_helper'

RSpec.describe UserNotesController do

  context 'GET #index' do

    let(:note) { build(:user_note) }

    specify 'populates an array of notes' do
      expect(:user_notes).to eq [note]
    end

    specify 'renders the :index view' do
      get :index
      expect(response).to render_template :index
    end
  end
end

不知道为什么它没有通过,但我收到了这条消息。

(compared using ==)

Diff:
@@ -1,2 +1,2 @@
-[#<UserNote id: nil, user_id: 2, creator_id: nil, note: "Magnam quas fugit nihil.", created_at: nil, updated_at: nil, follow_up: nil>]
+:user_notes

我对 Rspec 还是很陌生。有什么帮助吗?

【问题讨论】:

  • 你没有描述你用什么来模拟数据库。

标签: ruby-on-rails ruby ruby-on-rails-3 rspec


【解决方案1】:

要在 rspect 测试中访问实例变量 @foo,请使用 assigns(:foo) 引用它

expect(assigns(:user_notes)).to eq [note]

您也错过了行动号召。应该是……

get :index
expect(assigns(:user_notes)).to eq [note]

最后,let(:note) { build(:user_note) } 是惰性的,在引用变量之前不会执行......这只是在 get :index 之后,并且 build 在任何情况下都不会保存到数据库中,所以将其更改为...

let!(:note) { create(:user_note) }

【讨论】:

  • 感谢您的建议,但仍然出现错误:expected: [#&lt;UserNote id: nil, user_id: 3, creator_id: nil, note: "Minima enim molestias dicta velit quo assumenda ea ...", created_at: nil, updated_at: nil, follow_up: nil&gt;]got: nil
  • 啊...你还需要在期望之前做get :index :)
  • @SteveTurczyn 将其添加到答案中,因为这是规范的第一个问题
  • 或许改成let(:note) { create(:user_note) }
  • [] 是一个好兆头。 :) 但是直到在测试中明确引用了 note 变量之后才会创建记录。修改了我的回答,建议您使用“让!”而不是 let
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-31
  • 1970-01-01
  • 2017-01-24
相关资源
最近更新 更多