Rails:如何使用RSpec测试数组的顺序

时间:2013-05-18 02:18:41

标签: ruby-on-rails rspec rspec-rails

我是RSpec的新手所以我正在寻找一个简单测试的帮助:

# 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

有人可以帮我一个声明检查阵列是否正确排序?

1 个答案:

答案 0 :(得分:3)

my_array.should eq expected_array

这将确保每个项目都在完全相同的位置。如果要检查数组是否具有与另一个数组相同的元素,但顺序无关紧要,请执行以下操作:

my_array.should =~ expected_array

因此,在您的特定情况下,您首先需要对get操作执行show,然后检查变量。这是这样做的:

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

有关详细信息,请查看RSpec's GitHub page