我想在rspec控制器测试中设置Rails.cache,但是在控制器方法中缓存总是空白的。这样做的方法是什么?
用户模型
def user_token
Rails.cache.fetch(id)
end
用户控制器
if current_user.user_token
@user = @account.users.find(params[:id])
@user.revoke_seat(:admin, current_user)
render :template => "/admin/users/revoke_seat"
else
render :js => "window.location.href='#{server_url}/oauth/authorize?response_type=code&client_id=#{client_id}&state=#{request.referrer}?auto_revoke_seat=true&redirect_uri=#{auth_service_callback_url}";
end
Rspec的
before do
users(:admin).stub(:internal_admin?).and_return(true)
login_as :admin
Rails.cache.write(user.id, "testToken", expires_in: 2.minutes)
end
it "should redirect to authentication service to generate access token" do
expect(user).to receive(:user_token).and_return(true)
xhr :put, :revoke_seat, account_id: account.id, id: user.id
expect(response).to render_template('admin/users/revoke_seat')
expect(assigns(:account)).to eq(account)
expect(assigns(:user)).to eq(user)
end
答案 0 :(得分:0)
我会将before方法更改为:
before do
users(:admin).stub(:internal_admin?).and_return(true)
login_as :admin
allow(Rails.cache).to receive(:fetch).with(user.id).and_return("testToken")
end