簡體   English   中英

Redis和Rails的Rspec測試失敗

[英]Failing Rspec tests with Redis and Rails

我重構了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數據庫,該數據庫在每個規范運行之前都會被刷新。 據我所知,該規范仍然應該通過。 我在這里想念什么嗎?

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

應該改為

to change(other_user.followers, :count).by(1)

這可能是重裝問題嗎? 嘗試這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM