存储在创建用户后调用的方法

时间:2015-02-27 20:51:34

标签: ruby-on-rails rspec

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

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})

1 个答案:

答案 0 :(得分:0)

我是否理解正确的问题是您在规范中可用的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