Marco Song Marco Song - 2 months ago 16
Ruby Question

Rails: Rspec user index admin user not included

Factory user.rb

FactoryGirl.define do
factory :user do
username "Matin"
password "123456"

factory :admin do
admin true
end
end
end


user_controller_spec.rb


before :each do
session[:user_id] = create(:admin).id
end

describe "user access to orders" do

describe "GET#index" do
it " populates an array of all users" do
smith = create(:user,username:'smith')
jones = create(:user,username:'jones')
get :index
expect(assigns(:users)).to match_array([smith, jones])
end
it "render the :index template" do
get :index
expect(response).to render_template :index
end
end


This can not pass test and show error


expected collection contained:[User id: 2, username: "smith"]
actual
collection contained: [User id: 1, username: "Matin"]
the extra
elements were: [User id: 1, username: "Matin"]


I think error happens because I did not put admin user into
match_array
.
How to add admin user into
match_array
?

Answer

You can save admin user to variable and then use it:

before :each do
  @admin = create(:admin)
  session[:user_id] = @admin.id
end

...

    get :index
    expect(assigns(:users)).to match_array([@admin, smith, jones])
Comments