RSpec: 难以测试索引操作中对象数组对不同用户的分配

RSpec: difficulty testing the assignment of an array of objects in the index action for different users

我正在编写规范来测试我的阅读列表控制器。阅读列表有一个 user_id 和一个 micropost_id。我正在尝试创建 2 个不同的用户并测试索引操作是否会显示用户阅读列表的列表。下面的测试一直有效,直到它到达用户 2 的最后一个测试 - 预期的是 reading_list_two 但它得到的是对应于 reading_list_one 的@microposts 但我不明白为什么。我确信这是一个简单的逻辑问题,但我看不到。

  RSpec.describe ReadingListsController, type: :controller do

   before(:example) do
    login_member
    @user = @member.user
    @another_user = create(:user)
    @micropost = create(:micropost)
    @another_post = create(:micropost)
   end

  describe "Reading list index action" do

  before(:example) do
    create_list(:reading_list, 3, user_id: @user.id, micropost_id: @micropost.id )
    create_list(:reading_list, 3, user_id: @another_user.id, micropost_id: @another_post.id)
   @reading_list_one = ReadingList.where(:user_id => @user.id)
   @reading_list_two = ReadingList.where(:user_id => @another_user.id)
  end

     let(:reading_lists) { @reading_list_one.map {|p| Micropost.find(p.micropost_id)} }

     let(:reading_lists_two) { @reading_list_two.map {|p| Micropost.find(p.micropost_id)} }


  it "assigns all the reading lists for user one to the @microposts" do
    get(:index, :user_id => @user.id)
    expect(reading_lists.size).to eq(3)
    expect(assigns['microposts'].to_a).to eq(reading_lists.to_a)
  end

  it "assigns all the reading lists for user two to the @microposts" do
    get(:index, :user_id => @another_user.id)
    expect(reading_lists_two.size).to eq(3)
    expect(assigns['microposts'].to_a).to eq(reading_lists_two.to_a)
  end
 end
end

这是 reading_list 控制器中的索引操作。

def index
     reading_list = current_user.reading_lists
     @microposts = reading_list.map {|p| Micropost.find(p.micropost_id)}.paginate(page: params[:page], :per_page => 10)
end

current_user 通常 return 登录的用户,在这种情况下,您的 index 方法将始终 return 任何登录用户的微博您的 login_member 方法在外部 before 块中。

您可以通过以 @another_user 身份登录进行第二次测试,或者将您的 index 方法更改为 return 微博,以便在 URL.