Search code examples
ruby-on-railsruby-on-rails-3rspeccapybararspec-rails

Functional Testing for Customer Parameter Validation - Rspec / Capybara


I Added customer validation in my controller like

def customer_create
  if params[:api_key].present?
    ## Create Customer
  else
    ## Render Error Message in Json format
  end
end

How can I write Rspec Testing for above method?

Thanks In Advance


Solution

  • presumably customer_create is called from your controller's create action?

    So it might be sufficient to simply test that action.

    describe CustomersController do
      it "creates customer if :api_key is present` do
        post :create, api_key: "present key", customer_attributes
        expect(Customer.count).to eq 1
      end
    
      it "does not create customer if :api_key is absent` do
        json_error = {
                      key1: 'value1',
                      key2: 'value2'
                     }.to_json
        post :create, customer_attributes
        expect(response.body).to eq json_error
      end
    end
    

    You can test the method directly, if you set up the params.

    describe CustomersController do
      it "creates customer if :api_key is present' do
        controller.params[:api_key] = 'present key'
        controller.params.merge!(customer_attributes)
        controller.customer_create
        expect(Customer.count).to eq 1
      end
    end
    

    Both examples assume customer attributes hash is stored in a variable customer_attributes