Rails:不包括Rspec用户索引管理员用户

时间:2016-09-08 04:10:30

标签: ruby-on-rails ruby rspec

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

这无法通过测试并显示错误

  

预期收集包含:[用户ID:2,用户名:"史密斯"]实际   包含的集合:[用户ID:1,用户名:" Matin"]额外   元素是:[用户ID:1,用户名:" Matin"]

我认为错误发生是因为我没有将管理员用户放入match_array
如何将管理员用户添加到match_array

1 个答案:

答案 0 :(得分:2)

您可以将admin用户保存到变量,然后使用它:

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

...

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