如何对rspec控制器测试的stub模型方法

时间:2017-05-23 05:30:40

标签: ruby-on-rails-3 rspec rspec-rails

我正在尝试将我在控制器中使用的模型方法存根,但它似乎永远不会起作用。有人能让我知道正确的方法吗

用户控制器

 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
    user.stub(:user_token).and_return("123123")# THIS IS NOT WORKING
  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

1 个答案:

答案 0 :(得分:0)

您可以尝试使用allow方法而不是stub。例如,allow(:admin).to receive(:internal_admin?).and_return(true)