Frage

I have the following code:

def self.create_new_tenant(tenant_params, user_params, coupon_params)
  tenant = Tenant.new(:name => tenant_params[:name])
  if new_signups_not_permitted?(coupon_params)
    raise ::Milia::Control::MaxTenantExceeded, "Sorry, new accounts not permitted at this time" 
  else 
    tenant.save    # create the tenant
  end
  return tenant
end

and

 def self.new_signups_not_permitted?(params)
   return false
 end

How can I write Rspec testing for If conditions is true and false in both the case.

thanks in advance

War es hilfreich?

Lösung

First, I think you could change your methods to something like that:

def self.create_new_tenant(tenant_params, coupon_params)
  unless new_signups_permitted?(coupon_params)
    raise ::Milia::Control::MaxTenantExceeded, "Sorry, new accounts not permitted at this time"
  end

  tenant = Tenant.new(:name => tenant_params[:name])
  tenant.save! # Use the "bang" method or check the return value
  tenant
end

def self.new_signups_permitted?(params)
  false
end

You don't need to explicitly return a value in that cases nor initialize a tenant if new signups aren't permitted.

I have changed the name of your last method from new_signups_not_permitted? to new_signups_permitted?, because it's more clear, I think.

BTW, I remove user_params because you aren't using it.

This is an example of what you need. Probably it doesn't work like that.

describe ".create_new_tenant(tenant_params, coupon_params)" do
  context "when new signups are permitted" do
    before(:each) do
      allow(<Model>).to receive(:new_signups_permitted?) { true }
    end
    it "..." do
      expect { 
        <Model>.create_new_tenant(<tenant_params>, <coupon_params>)
      }.to change(Tenant, :count).from(0).to(1)
    end
  end
  context "when new signups aren't permitted" do
    before(:each) do
      allow(<Model>).to receive(:new_signups_permitted?) { false }
    end
    it "..." do
      expect { 
        <Model>.create_new_tenant(<tenant_params>, <coupon_params>)
      }.not_to change(Tenant, :count)
    end
    it "..." do
      expect { 
        <Model>.create_new_tenant(<tenant_params>, <coupon_params>)
      }.to raise_error "Sorry, new accounts not permitted at this time"
    end
  end
end

You have to define the conditions you need in .new_signups_permitted? because I supose you don't want it always returns false.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top