1

我是 Rspec 的新手,对 RoR 也很陌生。话虽如此,我已经用尽了所有的选择来试图让它发挥作用。我在方法中有一个变量,可以Usercreate我的UserController.rb. 此变量从身份验证方法获取数据。然后,我使用这个局部变量,它是来自 API 调用的响应,根据变量参数创建用户。据我所知,我已经尝试了所有关于 Rspec 的知识,但没有太多运气。我不断收到错误,因为数据变量为零,因为我存根/模拟了方法和变量。

如果有人可以帮助我弄清楚如何测试这个或将我链接到一个关于如何做到这一点的好教程(我读过很多),我真的很感激。

这是我的代码:

users_controller.rb

def get_google_data
  ...
  data = response.parsed #OAuth2 

  @id = data['id']
  @email = data['email']
  @fname = data['given_name']
  @lname = data['family_name']
end

def create
  get_google_data
  puts "Got google data"
  puts @id
  if !@id.nil?
    puts "data is not nil"
    @user = User.find_by_google_id(@id)
    puts @user

    if @user.nil?
      puts "inside user condition"
      @user = User.new(:email => @email, :google_id => @id,
                       :first_name => @fname,
                       :last_name => @lname)

      if @user.save
        render json: @user, status: :created, location: @user
      else
        render json: @user.errors, status: :unprocessable_entity
      end
    else
      puts "ended in the right Place"
      render json: @user, location: @user
    end
  end
end

users_controller_spec.rb

describe "should not create duplicate user" do
  it "returns user object that was previously created" do
    @user = mock_model(User, :google_id=>1)
    #controller.should_receive(:get_google_data).and_return(:true)
    controller.instance_variable_set(:@id, 1)
    User.stub!(:find_by_google_id).with(1).and_return(@user)

    post :create
    @user.should_not be_nil
  end
end

我有2个问题。

  1. 测试失败,因为我无法控制数据data['id']和以下分配。

    Failure/Error: post :create
     NoMethodError:
       undefined method `[]' for nil:NilClass
     # ./app/controllers/users_controller.rb:109:in `get_google_data'
     # ./app/controllers/users_controller.rb:118:in `create'
     # ./spec/controllers/users_controller_spec.rb:6:in `block (3 levels) in <top (required)>'
    
  2. return 的调用给@user了我一个循环引用错误:

    2) UsersController should not create duplicate user returns user object that was previously created
     Failure/Error: post :create
     ActiveSupport::JSON::Encoding::CircularReferenceError:
       object references itself
     # ./app/controllers/users_controller.rb:141:in `create'
     # ./spec/controllers/users_controller_spec.rb:24:in `block (3 levels) in <top (required)>'
    
4

0 回答 0