Shobit
Shobit

Reputation: 794

How do I get this very simple rspec test to pass?

I'm relatively new to Rails and RSpec. I spent a lot of time trying to understand the basics of RSpec, WebMock, stubs, and other related things I thought would help me, but I just can't get this test to pass. I'm pretty sure this is a very simple and common test, but unfortunately I've now reached a point where I'm just randomly trying all options and hoping one would work by trial-and-error.

I have a very simple controller whose index action calls a service like this:

def index
  @some_var = @some_service.status # defined at rails-root/lib/services/SomeService.rb
  render :index
end

Of course, if I want to test this action, I would not want to make an actual service call. But I want to make sure @some_var is being set right. Therefore, I'm trying to write this:

  describe 'GET index' do
    it 'should set some_var' do
      @some_service.stub!(:status).and_return("aloha")
      get :index
      assigns(:some_var).should == "aloha"
    end
  end

As some of you might have guessed already, this gives me

expected: "aloha"
got: nil (using ==)

I think I'm not stubbing the service correctly. Could some one please help? Thanks.

Upvotes: 1

Views: 81

Answers (1)

Muntasim
Muntasim

Reputation: 6786

If you want to stub any instance variable in controller you can get it by:

controller.stub(:some_var).and_return('aloha')

To stub model instance better you could have:

SomeService.any_instance.stub(:status).and_return("aloha")

Upvotes: 2

Related Questions