我重构了我的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数据库,在每个规范运行之前刷新。据我所知,规格仍应该通过。我在这里错过了什么吗?
答案 0 :(得分:0)
to change(user.followers, :count).by(1)
应改为
to change(other_user.followers, :count).by(1)
答案 1 :(得分: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