存根创建用户后调用的方法

Stubbing a method thats called after a user is created

我正在尝试存根代码中的一个方法:

def create
  @user = Xaaron::User.new(user_signup_params)
  if save_new_user(@user)
    user = User.find(@user.first_name.parameterize)
    user_info_to_publish = {user_name: user.user_name, first_name: user.first_name, auth_token: user.auth_token, email: user.email}
    response = Xaaron::Publishers::Users.publish_new_user(user_info_to_publish)

    if response == 200
      user.set_published_user(true, false, 'create')
      redirect_to login_path
    else
      user.set_published_user(false, true, 'create')
      flash[:error] = 'Something went wrong in publishing your information to the applications you can interact with. We are aware of the issue and are on it.'
      redirect_to login_path
    end
  else
    render :new
  end
end

有问题的方法是 Xaaron::Publishers::Users.publish_new_user(user_info_to_publish) 我需要存根这个方法,这样我就可以检查以确保一切正常工作。

有问题的测试是:

it "should create a new user" do
  expect(Xaaron::Publishers::Users).to receive(:publish_new_user).with(
    {first_name: @user.first_name, user_name: 'johnq', email: @user.email, auth_token: @user.auth_token}
  ).and_return nil

  post :create, user: {
    first_name: @user.first_name, user_name: 'johnq',
    email: @user.email, email_confirmation: @user.email,
    password: 'SamplePassword', password_confirmation: 'SamplePassword'
  }

  expect(response).to redirect_to login_path
end

这个测试会因为一件事而失败,auth_token。我把它设置为在数据库中设置用户之前生成。 @user 通过以下方式完成:@user = FactoryGirl.build(:user)

我要如何更改测试才能通过?

更新

我应该包括这个:

测试失败,因为:

  Xaaron::Publishers::Users received :publish_new_user with unexpected arguments
         expected: ({:first_name=>"Adam", :user_name=>"johnq", :email=>"user72@example.com"})
              got: ({:user_name=>"johnq", :first_name=>"Adam", :auth_token=>"KrGN3zu3kQJQdyh8JHl_XA", :email=>"user72@example.com", :auth_token=>nil})

我的理解是否正确,问题是您在规范中提供的 auth_token 不是用于进行 Xaaron 调用的那个?如果是这样,您可以更改规范以仅检查某些参数。也就是说,检查除 auth_token.

以外的所有内容
expect(Xaaron::Publishers::Users).to receive(:publish_new_user).with(
  hash_including(first_name: @user.first_name, user_name: 'johnq', 
                 email: @user.email)).and_return nil

参见:http://www.rubydoc.info/gems/rspec-mocks/frames#Argument_Matchers