Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing 如何在rspec控制器测试中存根局部变量_Unit Testing_Ruby On Rails 3_Rspec - Fatal编程技术网

Unit testing 如何在rspec控制器测试中存根局部变量

Unit testing 如何在rspec控制器测试中存根局部变量,unit-testing,ruby-on-rails-3,rspec,Unit Testing,Ruby On Rails 3,Rspec,我刚刚实现了OmniAuth(使用Ryan Bates的屏幕广播),正在为该功能编写Rspec测试,在测试authentifications#create action时遇到了麻烦。对于如何测试这一点,我感到非常困惑——特别是如何存根局部变量omniauth。不管我怎么做,我都无法让任何测试正常进行 举一个动作的简化版本为例,您将如何测试用户是否调用了一个新动作 #cut down version of the authentifications controller code I am at

我刚刚实现了OmniAuth(使用Ryan Bates的屏幕广播),正在为该功能编写Rspec测试,在测试authentifications#create action时遇到了麻烦。对于如何测试这一点,我感到非常困惑——特别是如何存根局部变量omniauth。不管我怎么做,我都无法让任何测试正常进行

举一个动作的简化版本为例,您将如何测试用户是否调用了一个新动作


#cut down version of the authentifications controller code I am attempting to test

  def create
    omniauth = request.env["omniauth.auth"]
    authentification = Authentification.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])     
    ....
    user = User.new
    ....
  end  

#example test

    it "should create a new user" do          
        subject.stub_chain(:request,:env) {{"omniauth.auth" => {'provider' =>1, 'uid' => 2}}}
        User.should_receive(:new)
        post :create
      end

#我尝试测试的authentifications控制器代码的缩减版本
def创建
omniauth=request.env[“omniauth.auth”]
authentication=authentication.find_by_provider_和_uid(omniauth['provider'],omniauth['uid'])
....
user=user.new
....
结束
#示例测试
它“应该创建一个新用户”吗
subject.stub_chain(:request,:env){{{“omniauth.auth”=>{'provider'=>1,'uid'=>2}}}
用户应接收(:新建)
帖子:创建
结束

我做到了:

class SessionsController < ApplicationController 
  def create 
    @user = User.find_by_auth_hash(auth_hash) 
  end 

  def auth_hash 
    request.env['omniauth.auth'] 
  end 
end 

describe SessionsController do 
  it 'should allow login' do 
    controller.stub!(:auth_hash).and_return({'provider' => 'twitter', 'uid' => '1234'}) 
    get :create, :provider => 'twitter' 
    assigns(:user).should_not be_nil 
  end 
end 
class sessioncontroller'twitter','uid'=>'1234'})
获取:create,:provider=>'twitter'
分配(:用户)。不应为零
结束
结束

希望有帮助

auth_散列的那个漂亮的小重构做得很好。