DRY rspec测试与路由

时间:2018-04-20 23:06:06

标签: ruby-on-rails-4 rspec routing rspec-rails

我花了几个小时试图让我的rspec测试工作。结果我没有真正想要以某种方式进行优化的DRY测试。

它们如下所示:

describe ExtApi::BaseController do
  let!(:app)    { create(:api_application) }
  let!(:token)  { app.token }

  controller do
    def resp
      render json: {foo: 'bar'}
    end

    def error
      raise StandardError 'baz'
    end
  end

  describe '#authenticate' do
    context 'when is successfull' do
      it 'renders bar' do
        routes.draw { get '/foo'  => 'ext_api/base#resp' }
        get :resp,  access_token: token
        expect ...
      end
    end

    context 'when token is invalid' do
      before do
        app.destroy
      end

      it 'renders error' do
        routes.draw { get '/foo'  => 'ext_api/base#resp' }
        get :resp, access_token: token
        expect ...
      end

      it do
        routes.draw { get '/foo'  => 'ext_api/base#resp' }
        get :resp, access_token: token
        is_expected.to respond_with 401
      end
    end

    context 'when token is not presented' do
      it 'renders error' do
        routes.draw { get '/foo'  => 'ext_api/base#resp' }
        get :resp
        expect ...
      end

      it do
        routes.draw { get '/foo'  => 'ext_api/base#resp' }
        get :resp
        is_expected.to respond_with 401
      end
    end
  end

我必须在每个routes.draw块中重复it(而不是before),否则,它会破坏所有路由,并且在所有路由之后运行的所有测试中,我得到RoutingError

所以,我想知道有没有办法比我更好地做到这一点?

(我使用rails 4.2rspec 3.4

1 个答案:

答案 0 :(得分:0)

如果将每个控制器测试分成不同的块,则可以这样做。

if let lbl = self.view.viewWithTag(1 /*your UILabel tag*/) as? UILabel {
    lbl.text = "some text"
}

参考:https://relishapp.com/rspec/rspec-rails/docs/controller-specs