尝试使用 get :index 检索记录,基于用户,没有任何返回。响应正常

Trying to retrieve a record with get :index, based on user, nothing getting returned. Response OK

我正在尝试根据用户 ID 检索记录。确保我的 get 控制器的索引正常工作。这是我的控制器片段。

class SimulationsController < ApplicationController

    def index
        if current_user 
            @simulations = current_user.simulations
        else 
            redirect_to new_user_session_path, notice: 'You are not logged in.'
        end
    end

现在我在下面的控制器规范中添加了一些痕迹。从我从这些痕迹中收集的信息来看,有四个模拟存在用于 User_ID 1 的测试,但是为测试创建的用户以及测试中的记录都是 User_ID 5. 任何人都可以提供一些指导吗?我很困惑地为此苦苦思索。此外,我收到回复:好的。编辑:使用以下答案更新规范。

require 'spec_helper'

describe SimulationsController, :type => :controller do

    let :user do 
        FactoryGirl.create(:user)
    end

    before(:each) do
        puts "~#{user.id}"
        sign_in user    
    end

    describe "GET #index" do 

        it "returns the correct number of simulations" do 
            simulation = FactoryGirl.build(:simulation, user: user)
            simulation.save!
            puts "@@@@#{simulation.user_id}"

            puts user.id
            Simulation.all.each do |sim| 
                puts sim.user_id
            end

            get :index
            puts "---\t\t#{response.body.size}"
            # expect(response).to be_success            
        end

    end

end

编辑 2:

用户工厂:

FactoryGirl.define do
    factory :user do
        email "user_#{User.last.nil? ? 1 : User.last.id + 1}@home.com"
        password "password"
    end
end

模拟工厂:

FactoryGirl.define do 
    factory :simulation do |f|
        f.id (Simulation.last.nil? ? 1 : Simulation.last.id + 1)
        f.x_size 3
        f.y_size 3
        f.user_id 1
    end 
end 

最终编辑:我正在检查错误,如下所述,Body 不是我要找的东西我想像下面那样使用分配来检查我想要的东西:

    it "returns the correct number of simulations" do 
        simulation = FactoryGirl.build(:simulation, user: user)
        simulation.save!

        get :index

        expect(assigns(:simulations).size).to eq 1
    end

可能 FactoryGirl 覆盖了您的 user_id 分配,因为您在那里设置了 association :user。只需将 user_id 更改为 user 就可以了:

simulation = FactoryGirl.build(:simulation, user: user)

UPD。并修复你的工厂:

FactoryGirl.define do 
    factory :simulation do |f|
        # Never set ID manually
        # f.id (Simulation.last.nil? ? 1 : Simulation.last.id + 1)
        f.x_size 3
        f.y_size 3
        # f.user_id 1
        # user 'association' method to set up associations
        f.association :user
    end 
end

UPD2。要检查控制器是否正确分配了变量,请使用 assigns:

expect(assigns(:simulations).length).to eq 4

您几乎不应该将您的 response.body 与任何东西进行比较 – 因为,好吧,它只是原始的 body。要测试您的观点,您可以使用特殊的期望方法,并检查实例 @-您使用 assigns.

的变量赋值

response.body 是呈现的 HTML,因此它的大小就是该字符串的长度。根据您的视图的外观,其大小与呈现的模拟数量之间可能没有直接的相关性。

此外,默认情况下 rspec 根本不会在控制器规范中呈现视图,因此 response.body 将始终为空字符串。您可以通过将 render_views 添加到示例组来更改此设置。