控制器测试Rspec,Rails 4.2

时间:2015-10-30 19:25:21

标签: ruby-on-rails ruby rspec

我刚开始使用RSpec而且我有点迷失了。谁能告诉我如何为这种方法编写控制器测试?

def list_c
    @c = params.has_key?(:car) ? Car.new(car_listing_params) : Car.new()
    @car.user = @user
    @car.number_of_beds = 4 unless @car.number_of_beds
    @car.car_type_tag = 'car' unless @car.car_type
    @page_title = t('home.list_your_car')
end

1 个答案:

答案 0 :(得分:0)

使用rspec进行控制器测试的一个小例子。你可以从这里得到一些想法     #在这里定义你的助手。     要求' rails_helper'

# respect method to define test for your controller.
RSpec.describe YourController, type: :controller do
   #define your factories for the set of your test
   # you will decide which one you need to create from factory. Factory girl
   # is used to mock factories.
   # @c = params.has_key?(:car) ? Car.new(car_listing_params) : Car.new()
   # @car.user = @user
   # @car.number_of_beds = 4 unless @car.number_of_beds
   # @car.car_type_tag = 'car' unless @car.car_type
   # @page_title = t('home.list_your_car')

   let(:user) { FactoryGirl.create :user }

   before { sign_in user }

  describe '#title' do
    context 'with valid params' do
      before do
        # in before block, you can request a http call 
        # with parameter. This action repeats before each test runs.
        get :your_action_of_current_controller, {a_param: a_value, a_date: "16-4-2015"}
      end

      it "renders successfully" do
        # when you call a get request it assigns a response object.
        expect(response).to be_success
      end

      it "returns json" do
       expect(response.content_type).to be == 'application/json'
      end
    end
   end 
 end