如何使用RSpec存根控制器实例变量?

时间:2015-06-06 12:20:00

标签: ruby-on-rails-3 rspec controller

new_controller_spec.rb

require 'spec_helper'

describe NewController do

  describe 'actions' do 

    describe 'POST /franchise_opportunities' do  
     it 'renders v3/franchise_opportunities when domain id 5' do
        domain = double(Domain, mrdeliverycom?: true)
        controller.instance_variable_set(:@domain, domain)

        post :franchise_opportunities, name: 'v'
        response.should render_template('v3/franchise_opportunities')
      end
    end
  end
end

new_controller.rb

# -*- encoding : utf-8 -*-
class NewController < ApplicationController
 before_filter { @domain = ... }
 def franchise_opportunities

    t = Logger.new(STDOUT)
    t.debug '=============================================='
    t.debug @domain
    t.debug @domain.mrdeliverycom?
    t.debug '=============================================='

    render :layout=>'v3', :template=>'v3/franchise_opportunities' and return if @domain && @domain.mrdeliverycom?

    @errors={}
    @post = params.clone
    ...

 end
end

日志

    ==============================================
#<Domain id: 1, name: "hettingersawayn.org", email: "alfonso.carroll@eichmanngrady.name", created_at: "2015-06-06 13:11:49", updated_at: "2015-06-06 13:11:49", domain_name: "ziemann.info8732", logo: nil, favicon: nil, slogan: nil, meta_title: nil, meta_keywords: nil, meta_description: nil, about_us: nil, smtp_server: "smtp.gmail.com", smtp_port: "587", smtp_username: nil, smtp_password: nil, smtp_authentication: "plain", smtp_tls: true, background: nil, source: "web", mobile_logo: nil, show_chef: false, ios_icon: nil, intro_text: nil>
    nil
    ==============================================

似乎@domain变量是在spec方法中设置的,未覆盖@domain变量是在控制器的 before_filter 中设置的。

1 个答案:

答案 0 :(得分:1)

实际上,实例变量设置为您在示例中提供的值,但这是在before_filter执行之前发生的,因此最终会再次设置。

您可以将初始化从before_filter移动到控制器和存根中的方法,而不是:

before_filter { @domain = get_domain }

...

protected

def get_domain
  ...
end

...

expect(controller).to receive(:get_domain).and_return("stubbed value")