我想为我的索引方法编写一个测试,该方法考虑了登录用户并检查索引方法是否只显示属于该用户的帖子。
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
端
答案 0 :(得分:0)
方案:
大致如此:
@user = User.create
sign_in @user
10.times { Note.create(user: @user) }
10.times { Note.create }
get :index
assigns(:notes).should have(10).notes