I've refactored my Rails code to store user relationships in Redis instead of a Postgres database.
The code before:
# 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
The refactored code:
# 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
The refactored code works but my existing specs are failing now:
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
Which now results in:
Failure/Error: expect do
count should have been changed by 1, but was changed by 0
Rspec uses a different Redis database which gets flushed before each spec runs. As far as I can tell the spec should still be passing. Am I missing something here?
to change(user.followers, :count).by(1)
应该改为
to change(other_user.followers, :count).by(1)
Could this be a reload problem? Try this:
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
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.