1

我重构了我的 Rails 代码以将用户关系存储在 Redis 而不是 Postgres 数据库中。

之前的代码:

# user.rb

has_many :relationships, foreign_key: "follower_id", dependent: :destroy
has_many :following, through: :relationships, source: :followed

def follow!(other_user)
  relationships.create!(followed_id: other_user.id)
end

重构后的代码:

# user.rb

def follow!(other_user)
  rdb.redis.multi do
    rdb[:following].sadd(other_user.id)
    rdb.redis.sadd(other_user.rdb[:followers], self.id)
  end
end

def following
  User.where(id: rdb[:following].smembers)
end

重构的代码有效,但我现有的规范现在失败了:

describe "following a user", js: true do
  let(:other_user) { FactoryGirl.create(:user) }
  before { visit user_path(other_user) }

  it "should increment the following user count" do
    expect do
      click_button "Follow"
      page.find('.btn.following')
    end.to change(user.following, :count).by(1)
  end
end

现在导致:

Failure/Error: expect do
   count should have been changed by 1, but was changed by 0

Rspec 使用不同的 Redis 数据库,该数据库在每个规范运行之前被刷新。据我所知,规范应该仍然通过。我在这里错过了什么吗?

4

2 回答 2

0
to change(user.followers, :count).by(1)

应改为

to change(other_user.followers, :count).by(1)
于 2013-02-26T12:30:04.437 回答
0

这可能是重新加载问题吗?尝试这个:

it "should increment the following user count" do
  expect do
    click_button "Follow"

    # user object is now stale, reload it from the DB
    user.reload
  end.to change(user.following, :count).by(1)
end
于 2013-02-27T04:44:29.443 回答