如何编写rspec测试来检查索引返回的帖子是否归当前用户所有

时间:2015-07-08 02:45:30

标签: ruby-on-rails rspec functional-testing

我想为我的索引方法编写一个测试,该方法考虑了登录用户并检查索引方法是否只显示属于该用户的帖子。

Notes_controller_spec.rb

describe "GET #index" do

it "responds successfully with an HTTP 200 status code" do
  get :index
  expect(response).to be_success
  expect(response).to have_http_status(200)
end

it "renders the index template" do
  get :index
  expect(response).to render_template("index")
end

it "returns only posts by user" do




end

notes_controller.rb

class NotesController < ApplicationController
  before_action :set_note, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!
  # GET /notes
  # GET /notes.json
  def index
        @users = User.order(:created_at)
    Rails.logger.info("#{current_user.id == @users[0].id}")
        if current_user.equal? @users[0] 
            @notes = Note.all
        else
      @notes = Note.where(user: current_user)
        end
    respond_to do |format|
    format.nil? { }
    format.html { }
    format.xml {
        @users = User.order(:created_at)
        if @users.first == current_user then
            render xml: @notes
        else
            return head(:unauthorized)
        end
    }
    end
  end

1 个答案:

答案 0 :(得分:0)

方案:

  1. 您必须创建笔记
  2. 创建用户
  3. 然后验证用户
  4. 用户笔记计数的Ater检查次数:
  5. 大致如此:

    @user = User.create
    sign_in @user
    10.times { Note.create(user: @user) }
    10.times { Note.create }
    get :index
    assigns(:notes).should have(10).notes