Rspec testing of counter_cache column's returning 0

左心房为你撑大大i 提交于 2019-12-04 04:22:24

The counter_cache is getting updated in the database directly. This will not affect the copy of the model you have loaded into memory so you need to reload it:

it "media_count should == 1 " do 
  user.reload
  user.media_count.should == 1
end

But, I don't think that is how I would test this. As you have it, your test is very tightly coupled to setup code that seem like it doesn't need to be there at all. How about something like this for a stand alone spec:

it "has a counter cache" do
    user = FactoryGirl.create(:user)
    expect { 
      user.media.create(caption: "Test media") 
    }.to change { User.last.media_count }.by(1)
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!