简体   繁体   中英

Rails: How to Test an Array's Order with RSpec

I'm new to RSpec so I'm looking for a little help on a simple test:

# controller method
def show
  @group = Group.find(params[:id])
  @group_members = @group.group_members.order("posts ASC")
end

# in my rspec
it "should show order correctly" do
  @group = FactoryGirl.create(:group)
  @user_1 = FactoryGirl.create(:user, user_name: "Gary")
  @user_2 = FactoryGirl.create(:user, user_name: "Shawn")
  @user_3 = FactoryGirl.create(:user, user_name: "Gus")
  @user_4 = FactoryGirl.create(:user, user_name: "Jack")
  @group_member_1 = FactoryGirl.create(:group_member, group_id: @group.id, user_id: @user_1.id, posts: 30)
  @group_member_2 = FactoryGirl.create(:group_member, group_id: @group.id, user_id: @user_2.id, posts: 20)
  @group_member_3 = FactoryGirl.create(:group_member, group_id: @group.id, user_id: @user_3.id, posts: 10)
  @group_member_4 = FactoryGirl.create(:group_member, group_id: @group.id, user_id: @user_4.id, posts: 15)
  visit group_path(@group)

  # how do i assert the order of the array?
end

Can someone please help me with a statement to check that the array sorted correctly?

my_array.should eq expected_array

That will make sure that each item is in the exact same spot. If you want to check that an array has the same elements as another array, but the order doesn't matter, do this:

my_array.should =~ expected_array

So in your particular case, you first would need to do a get to the show action, then check the variable. That's done like this:

get :show, :id => @group.id
expected_group_members = [@group_member_3, @group_member_4, @group_member_2, @group_member_1]
assigns(:group_members).should eq expected_group_members

For more information, check out RSpec's GitHub page .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM