rspec shared_examples_for方法

时间:2013-06-25 12:36:46

标签: ruby-on-rails rspec

我有这个控制器spec文件。

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方法重新编码此测试,但我没有处理它。

1 个答案:

答案 0 :(得分: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