0

我有这个控制器规格文件。

describe BriefNotesController do
  render_views

  before(:all) do
    @customer=Factory(:customer)
    @project=Factory(:project_started, :owner => @customer)
  end

  context 'get :new' do

    it 'should redirect to login page for not signed in users' do
      get :new, :project_id => @project.id
      response.should new_user_session_path
    end


  end

  context 'get :create' do

    it 'should redirect to login page for not signed in users' do
      post :create, {:project_id => @project.to_param, :brief_note => Factory.attributes_for(:brief_note, :project_id => @project.id)}
      response.should redirect_to new_user_session_path
    end
end

在这些测试中,我对每个操作重复相同的身份验证测试,因此我想用干的方式重新编码它。我试图用shared_examples_for方法重新编码这个测试,但我没有处理它。

4

1 回答 1

0

像这样的东西可以工作

shared_examples_for 'redirects to login page if not signed in' do

  context 'get :new' do
    it 'should redirect to login page for not signed in users' do
      get :new, :project_id => resource.id
      response.should redirect_to new_user_session_path
    end
  end

  context 'get :create' do
    it 'should redirect to login page for not signed in users' do
      post :create, resource_params
      response.should redirect_to new_user_session_path
    end
  end
end

你会像这样使用它:

describe BriefNoteController do
  let(:customer) { Factory(:customer) }
  let(:project) { Factory(:project_started, :owner => customer) }

  let(:resource) { project }
  let(:resource_params) do
    {
      :project_id => project.to_param,
      :brief_note => Factory.attributes_for(:brief_note, :project_id => project.id)
    }
  end

  it_behaves_like 'redirects to login page if not signed in'
end
于 2013-06-25T12:48:57.243 回答