rspec将重复块转换为方法

时间:2013-06-18 10:40:44

标签: ruby-on-rails rspec

我的spec文件中有这个上下文。

  context 'get :index' do 
            it 'should be loaded successfully if current user is not customer' do
              sign_in @creative
              get :index
              response.should be_success 
            end
            it 'should redirect to root page if current user is customer' do 
              sign_in @customer
              get :index
              response.should redirect_to root_path
            end
          end

context 'post :create' do 
            it 'should be loaded successfully if current user is not customer' do
              sign_in @creative
              post :create
              response.should be_success 
            end
            it 'should redirect to root page if current user is customer' do 
              sign_in @customer
              post :create
              response.should redirect_to root_path
            end
          end

我在两个不同的上下文中重复相同的代码。我将它转换为此方法,但它不起作用。

def check_user_sign_in(request_type, action)
      context '#{request_type} :#{action}' do 
        it 'should be loaded successfully if current user is not customer' do
          sign_in @creative
          request_type action
          response.should be_success 
        end
        it 'should redirect to root page if current user is customer' do 
          sign_in @customer
          request_type action
          response.should redirect_to root_path
        end
      end
    end

  end

这里的问题是我没有使用参数作为方法名称。

你知道我怎么能用干的方式使用它?

1 个答案:

答案 0 :(得分:0)

这:

context '#{request_type} :#{action}' do 

将无效,因为字符串插值不会在单引号内进行求值。

您必须使用双引号

a = 'alpha' #=> "alpha"
b = 'beta'  #=> "beta"

'#{a} #{b}' #=> "\#{a} \#{b}"

"#{a} #{b}" #=> "alpha beta"