Reputation: 107
Let me first start of by saying that I'm a new person writing tests here, working with rails only for few weeks. Writing a rspec test for my phone verification. Here is some code first :
User.stub(:create).and_return(@user)
@user.stub(:send_sms).with('foo').and_return('bar')
sign_in @user
visit home_path
click_link 'Telephone verification'
Now this is the method in my user that I want to stub and return arbitrary value without actually going into the real method :
def send_sms
TWILIO_CLIENT.account.sms.messages.create(
:from => TWILIO_SMS_NUMBER,
:to => phone,
:body => "Verification code is: #{sms_code}"
)
end
Am I doing even doing the right thing here? I'm not even sure, I read so much stuff on this topic, still confused.
Since I don't have TWILIO_CLIENT initialized for test environment I get this error when I save_and_open_page :
uninitialized constant User::TWILIO_CLIENT
And so I want to stub the send_sms method, is that the right thing to do?
Upvotes: 2
Views: 1241
Reputation: 47558
I don't have TWILIO_CLIENT initialized for test environment
You'll need to define those constants somewhere. It should be as simple as:
TWILIO_CLIENT = double('twilio_client')
TWILIO_SMS_NUMBER = double('twilio_sms_number')
Now you can stub methods on the test doubles.
To stub the call itself, you can use stub_chain
:
TWILIO_CLIENT.stub_chain(:account, :sms, :messages, :create)
While this should work, whenever you see stub_chain
it suggests that you may want to refactor. In this case, you probably shouldn't be reaching into TWILIO_CLIENT and messing with its internals.
Upvotes: 2