RSpec check if method has been called - ruby-on-rails

I have an AccountsController and a destroy action. I want to test if the account is being deleted and if the subscription is being canceled.
AccountsController
def destroy
Current.account.subscription&.cancel_now!
Current.account.destroy
end
RSpec
describe "#destroy" do
let(:account) { create(:account) }
it "deletes the account and cancels the subscription" do
allow(account).to receive(:subscription)
expect do
delete accounts_path
end.to change(Account, :count).by(-1)
expect(account.subscription).to have_received(:cancel_now!)
end
end
But the above test does not pass. It says,
(nil).cancel_now!
expected: 1 time with any arguments
received: 0 times with any arguments
Because the account.subscription returns nil it is showing this. How do I fix this test?

You need to replace the account entity in the context of the controller to the account from the test
It could be
describe "#destroy" do
let(:account) { create(:account) }
it "deletes the account and cancels the subscription" do
allow(Current).to receive(:account).and_return(account)
# if the subscription does not exist in the context of the account
# then you should stub or create it...
expect do
delete accounts_path
end.to change(Account, :count).by(-1)
expect(account.subscription).to have_received(:cancel_now!)
end
end
Regarding subscription
expect(account).to receive(:subscription).and_return(instance_double(Subscription))
# or
receive(:subscription).and_return(double('some subscription'))
# or
create(:subscription, account: account)
# or
account.subscription = create(:subscription)
# or other options ...

Related

Rspec: How to test a method that raises an error

I have a SubscriptionHandler class with a call method that creates a pending subscription, attempts to bill the user and then error out if the billing fails. The pending subscription is created regardless of whether or not the billing fails
class SubscriptionHandler
def initialize(customer, stripe_token)
#customer = customer
#stripe_token = stripe_token
end
def call
create_pending_subscription
attempt_charge!
upgrade_subscription
end
private
attr_reader :stripe_token, :customer
def create_pending_subscription
#subscription = Subscription.create(pending: true, customer_id: customer.id)
end
def attempt_charge!
StripeCharger.new(stripe_token).charge! #raises FailedPaymentError
end
def upgrade_subscription
#subscription.update(pending: true)
end
end
Here is what my specs look like:
describe SubscriptionHandler do
describe "#call" do
it "creates a pending subscription" do
customer = create(:customer)
token = "token-xxx"
charger = StripeCharger.new(token)
allow(StripeCharger).to receive(:new).and_return(charger)
allow(charger).to receive(:charge!).and_raise(FailedPaymentError)
handler = SubscriptionHandler.new(customer, token)
expect { handler.call }.to change { Subscription.count }.by(1) # Fails with FailedPaymentError
end
end
end
But this does not change the subscription count, it fails with the FailedPaymentError. Is there a way to check that the subscription count increases without the spec blowing up with FailedPaymentError.
You should be able to use Rspec compound expectations for this
https://relishapp.com/rspec/rspec-expectations/docs/compound-expectations
So I'll re-write your expectation to something like this:
expect { handler.call }.
to raise_error(FailedPaymentError).
and change { Subscription.count }.by(1)
It can be done like this
expect{ handler.call }.to raise_error FailedPaymentError
Should work.
If you don't want to raise error at all then you can remove this line, and return a valid response instead
allow(charger).to receive(:charge!).and_raise(FailedPaymentError)
More info - How to test exception raising in Rails/RSpec?
Official RSpec docs
https://relishapp.com/rspec/rspec-expectations/v/2-0/docs/matchers/expect-error

How to access instance variables to test `receive` in a spec?

I have the following spec fragment:
it 'should create company and user' do
company_iv = assigns(:company)
user_iv = assigns(:user)
expect(subject).to receive(:create_timeline_event).with(company_iv, user_iv)
expect { post :create, params }.to change { User.count }.by(1).and change { Company.count }.by(1)
and traditionally use the receive syntax to test calling a method. I normally call it before the call to post in the above fragment. How would I access the instance variable of the user and the company for this spec?
Looks like you're trying to jam a few different tests into a single it statement. Here's how I would approach this:
it 'creates company and user' do
expect { post :create, params }
.to change { User.count }.by(1)
.and change { Company.count }.by(1)
end
it 'assigns instance variables' do
post :create, params
expect(assigns(:company)).to eq(Company.last)
expect(assigns(:user)).to eq(User.last)
end
it 'calls create_timeline_event with newly created company and user' do
allow(some_object).to receive(:create_timeline_event)
post :create, params
expect(some_object)
.to have_received(:create_timeline_event)
.with(Company.last, User.last)
end
Note that these tests are going to be slow because they hit the database. Another approach to this is to use mocks. That would look something like this:
let(:params) { ... }
let(:company) { instance_double(Company) }
let(:user) { instance_double(User) }
before do
allow(Company).to receive(:create).and_return(company)
allow(User).to receive(:create).and_return(user)
allow(some_object).to receive(:create_timeline_event)
post :create, params
end
it 'creates company and user' do
expect(Company).to have_received(:create).with(company_params)
expect(User).to have_received(:create).with(user_params)
end
it 'assigns instance variables' do
expect(assigns(:company)).to eq(company)
expect(assigns(:user)).to eq(user)
end
it 'calls create_timeline_event with newly created company and user' do
expect(some_object)
.to have_received(:create_timeline_event)
.with(company, user)
end
These tests do not hit the database at all, meaning that they'll execute much faster.

Rails response.should be_success is never true

I am following Michael Hartl's excellent tutorial on Ruby on Rails. I'm stuck trying to understand the way ActionDispatch::Response works. This derives from Exercise 9 of Chapter 9 (Rails version 3.2.3).
In particular we're asked to make sure that the admin user is unable to User#destroy himself. I have an idea how to do that, but since I'm trying to follow a TDD methodology, I'm first writing the tests.
This is the relevant snippet in my test:
describe "authorization" do
describe "as non-admin user" do
let(:admin) {FactoryGirl.create(:admin)}
let(:non_admin) {FactoryGirl.create(:user)}
before{valid_signin non_admin}
describe "submitting a DELETE request to the Users#destroy action" do
before do
delete user_path(admin)
#puts response.message
puts response.succes?
end
specify{ response.should redirect_to(root_path) }
specify{ response.should_not be_success }
end
end
#Exercise 9.6-9 prevent admin from destroying himself
describe "as admin user" do
let(:admin){FactoryGirl.create(:admin)}
let(:non_admin){FactoryGirl.create(:user)}
before do
valid_signin admin
end
it "should be able to delete another user" do
expect { delete user_path(non_admin) }.to change(User, :count).by(-1)
end
describe "can destroy others" do
before do
puts admin.admin?
delete user_path(non_admin)
puts response.success?
end
#specify{response.should be_success}
specify{response.should_not be_redirect}
end
describe "cannot destroy himself" do
before do
delete user_path(admin)
puts response.success?
end
#specify{response.should_not be_success}
specify{response.should be_redirect}
end
end
.
.
.
end
All the tests pass except the "can destroy others" test.
However, if I puts response.success? after every delete request, I always get False, so none of the requests "succeed".
Manually interacting with the webapp and deleting users works just fine, so I assume that response.success does not mean that the detroy(or whatever request for that matter) was not successful, but something else. I read it has to do with the difference between HTTP responses 200/302/400, but I'm not totally sure.
For the record, this is my User#destroy:
def destroy
User.find(params[:id]).destroy
flash[:success]="User destroyed."
redirect_to users_path
end
Any light on this?
thanks!
Edit
This is my factory:
FactoryGirl.define do
factory :user do
sequence(:name){ |n| "Person #{n}" }
sequence(:email){ |n| "person_#{n}#example.com"}
password "foobar"
password_confirmation "foobar"
factory :admin do
admin true
end
end
end
Edit 2 as suggested by #Peter Alfvin, I changed lines
let(:user){FactoryGirl.create(:user)}
to
let(:admin){FactoryGirl.create(:admin)}
And all user to admin in general. I also added a puts admin.admin? before the delete request. Still not working!
Edit 3
Changing the test "can destroy others" as:
describe "can destroy others" do
before do
puts admin.admin?
delete user_path(non_admin)
puts response.success?
end
#specify{response.should be_success}
specify{response.should_not be_redirect}
end
Does not seem to help either.
For your "admin" case, you're still creating and logging in as a "regular" user instead of an admin user, which is why you can't destroy anyone else.
response.success does indeed refer to the HTTP response code. By default, I believe this is anything in the 200 range. redirect_to is in the 300 range.
Make sure your user Factory includes this line
factory :user do
#your user factory code
factory :admin do
admin true
end
end
Then FactoryGirl.create(:admin) will return an admin user or you can also use user.toggle!(:admin) which will switch a standard user to an admin user.
try this then
describe "as admin user" do
let(:admin){FactoryGirl.create(:admin)}
let(:non_admin){FactoryGirl.create(:user)}
before do
valid_signin admin
end
it "should be able to delete another user" do
expect { delete user_path(non_admin) }.to change(User, :count).by(-1)
end
it "can destroy others" do #
before do
puts admin.admin?
delete user_path(non_admin)
puts response.success?
end
#specify{response.should be_success}
specify{response.should_not be_redirect}
end
it "cannot destroy himself" do
before do
delete user_path(admin)
puts response.success?
end
#specify{response.should_not be_success}
specify{response.should be_redirect}
end
end
describe creates a magic Class it becomes a subClass of the describe class from my understanding. Rails has a lot of this magic and it can get confusing. Also I have not seen your controller but what are you expecting to happen when you destroy a user because if you followed the tutorial then there will be a redirect delete sent through the browser will call your destroy method in the UsersController which in the tutorial has this line redirect_to users_url so response.should_not be_redirect will always fail because the spec is wrong not the controller.

How to test after_destroy callback in Rails and RSpec?

I have this User class in Ruby on Rails:
class User < ActiveRecord::Base
after_destroy :ensure_an_admin_remains
private
def ensure_an_admin_remains
if User.where("admin = ?", true).count.zero?
raise "Can't delete Admin."
end
end
end
This works great and causes a database rollback if someone accidentally deletes an admin user.
The problem is that it seems to break the user delete action, even when testing with a non-admin user (generated by Factory Girl). This is my user_controller_spec.rb:
describe 'DELETE #destroy' do
before :each do
#user = create(:non_admin_user)
sign_in(#user)
end
it "deletes the user" do
expect{
delete :destroy, id: #user
}.to change(User, :count).by(-1)
end
end
Whenever I run this test, I get this error:
Failure/Error: expect{
count should have been changed by -1, but was changed by 0
There shouldn't be any error, though, because #user's admin attribute is set to false by default.
Can anybody help me out here?
Thanks...
I may be wrong but,
Your spec start with empty database right? So there is no admin user present in your db.
So when you call delete, you'll always have User.where("admin = ?", true).count equal to zero
Try creating an user admin before your test
describe 'DELETE #destroy' do
before :each do
create(:admin_user)
#user = create(:non_admin_user)
sign_in(#user)
end
it "deletes the user" do
expect{
delete :destroy, id: #user
}.to change(User, :count).by(-1)
end
end
I would make the following change:
before_destroy :ensure_an_admin_remains
def ensure_an_admin_remains
if self.admin == true and User.where( :admin => true ).count.zero?
raise "Can't delete Admin."
end
end
An alternative is to make the called function ensure_an_admin_remains a public function, such as check_admin_remains.
You can then test, the logic of check_admin_remains as if it were any other function.
Then in another test, you can ensure that function is called on destroy without any database interaction as follows:
let(:user) { build_stubbed(:user) }
it 'is called on destroy' do
expect(user).to receive(:check_admin_remains)
user.run_callbacks(:destroy)
end
You shouldn't raise for control flow. You can halt during callbacks to prevent the record being commited.
I've improved one some of the answers here for anyone else trying to work out how to do this properly as of Rails 5
class User < ActiveRecord::Base
before_destroy :ensure_an_admin_remains
private def ensure_an_admin_remains
return unless admin && User.where(admin: true).limit(2).size == 1
errors.add(:base, "You cannot delete the last admin.")
throw :abort
end
end

Check if a user is signed out in devise

I'm trying to check if an administrator is signed out in an Rspec test. However the usual signed_in? method can't be seen from rspec and isn't part of the RSpec Devise Helpers.
Something like this is what i have in place
before (:each) do
#admin = FactoryGirl.create(:administrator)
sign_in #admin
end
it "should allow the admin to sign out" do
sign_out #admin
##admin.should be_nil
##admin.signed_in?.should be_false
administrator_signed_in?.should be_false
end
Is there anothe way to check the session of the administrator and see if he's actually signed in or not?
it "should have a current_user" do
subject.current_user.should_not be_nil
end
Found at https://github.com/plataformatec/devise/wiki/How-To:-Controllers-and-Views-tests-with-Rails-3-%28and-rspec%29
I think it's really what you need How To: Test controllers with Rails 3 and 4 (and RSpec)
Just check current_user. It should be nil
Add. Good practice is using syntax like this
-> { sign_out #admin }.should change { current_user }.from(#admin).to(nil)
Not a new answer, really, but my rep isn't high enough to comment...:
If you've already overridden subject, the controller is available as controller in controller specs, so:
expect { ... }.to change { controller.current_user }.to nil
To check for a specific user, say generated by FactoryGirl, we've had good success with:
let(:user) do FactoryGirl.create(:client) ; end
...
it 'signs them in' do
expect { whatever }.to change { controller.current_user }.to user
end
it 'signs them out' do
expect { whatever }.to change { controller.current_user }.to nil
end
it "signs user in and out" do
user = User.create!(email: "user#example.org", password: "very-secret")
sign_in user
expect(controller.current_user).to eq(user)
sign_out user
expect(controller.current_user).to be_nil
end
You can refer this link devise spec helper link

Resources