为什么我的AR关系在RSpec中返回空,但在Rails控制台中返回对象?

时间:2015-05-07 23:04:16

标签: ruby-on-rails ruby-on-rails-4 rspec rspec3

这是我的规格:

<Dependencies>
    <TargetDeviceFamily Name="Windows.Universal"
                        MinVersion="1.0.22816.1"
                        MaxVersionTested="10.0.10069.0" />
    <PackageDependency Name="Microsoft.NET.CoreRuntime.1.0"
                       MinVersion="1.0.22816.1"
                       Publisher="CN=Microsoft Corporation, O=Microsoft Corporation,
                       L=Redmond, S=Washington, C=US" />
</Dependencies>

这与我的 describe 'GET #index' do let(:family_tree) { create(:family_tree, user: @user) } let(:node1) { create(:node, family_tree: family_tree, user: @user) } let(:node2) { create(:node, family_tree: family_tree, user: @user) } before { login_user } it "assigns all the nodes that are tagged with the current_user email to local variable 'tagged_nodes'" do get :index u1 = create(:user) u2 = create(:user) n1 = create(:node, family_tree: family_tree) n1.user_tag_list.add(u1.email, u2.email) expect(assigns(:tagged_nodes)).to include(n1) end end 有关,它正在测试此行的Dashboard#Index分配:

@tagged_nodes

以下是执行查找的方法,我将其存储在Concern中(正确包含在控制器中):

@tagged_nodes = nodes_that_are_tagged_with(current_user)

我得到的错误是:

  def nodes_that_are_tagged_with(user)
    Node.includes(:user_tags).tagged_with(user.email)
  end

请注意,返回的关系为空。

当我尝试在命令行运行此 1) DashboardController GET #index assigns all the nodes that are tagged with the current_user email to local variable 'tagged_nodes' Failure/Error: expect(assigns(:tagged_nodes)).to include(n1) expected #<ActiveRecord::Relation []> to include #<Node id: 21, name: "Miss Wendy McClure", family_tree_id: 38, user_id: nil, media_id: 21, media_type: "Video", created_at: "2015-05-07 22:56:09", updated_at: "2015-05-07 22:56:09", circa: "2015-05-25 00:00:00", is_comment: nil> Diff: @@ -1,2 +1,2 @@ -[#<Node id: 21, name: "Miss Wendy McClure", family_tree_id: 38, user_id: nil, media_id: 21, media_type: "Video", created_at: "2015-05-07 22:56:09", updated_at: "2015-05-07 22:56:09", circa: "2015-05-25 00:00:00", is_comment: nil>] +[] 查询时,我得到了我期望的正确结果:

Node.includes(:user_tags)...

对于我的生活,我无法弄清楚为什么规范会返回一个空关系。

1 个答案:

答案 0 :(得分:1)

问题是,在您已经点击索引操作后,您正在创建记录。将get :index移到记录创建之下:

it "assigns all the nodes that are tagged with the current_user email to local variable 'tagged_nodes'" do      
  u1 = create(:user)
  u2 = create(:user)
  n1 = create(:node, family_tree: family_tree)      
  n1.user_tag_list.add(u1.email, u2.email)

  get :index  

  expect(assigns(:tagged_nodes)).to include(n1)
end