class PollsController < ApplicationController
def index
@user = User.find(params[:user_id])
@polls = @user.polls.paginate(page: params[:page], :per_page =>
10).order(title: :DESC)
end
end
route:
user_polls GET /users/:user_id/polls(.:format)
polls#index
polls_controller_spec.rb:
RSpec.describe PollsController, type: :controller do
describe "GET #index" do
before :all do
@user = FactoryGirl.create(:user)
end
it "assign user as @user" do
get :index, user_id: @user.id
expect(assigns(:user)).to eq(@user)
end
it "assigns polls as @polls" do
get :index, user_id: @user.id
expect(assigns(:polls)).to eq([@poll])
end
it "redirects to the index view" do
get :index, user_id: @user.id
expect(response).to render_template("index")
end
end
end
class PollsController < ApplicationController
def index
@user = User.find(params[:user_id])
@polls = @user.polls.paginate(page: params[:page], :per_page =>
10).order(title: :DESC)
end
end
route:
user_polls GET /users/:user_id/polls(.:format)
polls#index
polls_controller_spec.rb:
RSpec.describe PollsController, type: :controller do
describe "GET #index" do
before :all do
@user = FactoryGirl.create(:user)
end
it "assign user as @user" do
get :index, user_id: @user.id
expect(assigns(:user)).to eq(@user)
end
it "assigns polls as @polls" do
get :index, user_id: @user.id
expect(assigns(:polls)).to eq([@poll])
end
it "redirects to the index view" do
get :index, user_id: @user.id
expect(response).to render_template("index")
end
end
end
Finished in 1.23 seconds (files took 2.81 seconds to load)
3 examples, 1 failure
Failed examples:
rspec ./spec/controllers/polls_controller_spec.rb:14 # PollsController
GET #index assigns polls as @polls
as you can see problem in test 'assigns polls as @polls'. I do not
understand why array @polls is empty
I think you need to add a factory for polls, and ensure that you assign a poll to that array before you test to see if there are any. Each test runs alone, and not in a predictable order unless you’ve disabled the test randomization feature in Rspec. Each test has a completely new and fresh look at the application, with no preconceived data to work with unless you provide it in your test, as you have done for the @user here.