在rspec测试中无法将符号转换为整数

时间:2012-12-04 19:50:54

标签: ruby-on-rails ruby-on-rails-3 rspec factory-bot

我正在编写一个简单的测试检查以查看我的控制器是否正常工作,但我的测试仍在继续

3) PasswordResetsController for checking update succeeds 
 Failure/Error: put :update, id: @user.password_reset_token
 TypeError:
   can't convert Symbol into Integer
 # ./app/controllers/password_resets_controller.rb:23:in `update'
 # ./spec/controllers/password_resets_controller_spec.rb:52:in `block (3 levels) in 
 <top (required)>'

我的测试如下......

describe PasswordResetsController do

before do
  @user = FactoryGirl.create( :user )
end

context "for checking update succeeds" do
  before do
    @user.password_reset_token = "gB5KGF-3hC4RNHCK5niz9A"
    @user.password_reset_sent_at = Time.zone.now
    @user.save!(validate: false) 
    put :update, id: @user.password_reset_token
  end


  it { should assign_to(:user) }      
  it { should respond_with(:redirect) }
  it { should redirect_to(signin_path) }
  it { should set_the_flash.to("Password has been reset.")}

end

end

以下是我的模型https://github.com/thejourneydude/template/blob/master/app/models/user.rb

的链接

编辑:问题似乎源于我的控制器。在我的本地服务器上,我带着

返回
TypeError in PasswordResetsController#update

can't convert Symbol into String

Rails.root: /home/jason/ror/template
Application Trace | Framework Trace | Full Trace

app/controllers/password_resets_controller.rb:19:in `update'

我的控制器代码中的更新操作是..

def update
  @user = User.find_by_password_reset_token!(params[:id])
  if @user.password_reset_sent_at && @user.password_reset_sent_at > 2.hours.ago
    redirect_to new_password_reset_path, flash: { error: "Password reset has expired" }
  elsif @user.update_attributes(params[:user])
    redirect_to root_url, flash: { success: "Password has been reset." }
  else 
    render :edit, flash: { error: "Hmm.. something went wrong. Let's try that again." }
  end
end

我的代码有什么问题,如何解决?

4 个答案:

答案 0 :(得分:1)

如果更改此行会发生什么:

redirect_to new_password_reset_path, flash[:error] = "Password reset has expired"

为:

redirect_to new_password_reset_path, flash: { error: "Password reset has expired" }

我的猜测是你不应该在flash[:error] =中调用redirect_to,因为Ruby中的赋值会返回分配的值。 redirect_to需要哈希作为第二个参数,但它被称为字符串。

答案 1 :(得分:1)

您没有传递:user参数,因此这行可能会给您一个错误:

elsif @user.update_attributes(params[:user])

尝试做:

before do
  put :update, :id => @user.password_reset_token, :user => valid_user_attributes
end

将valid_user_attributes设置为您想要的更新,例如{'email'=&gt; 'new_email@x.x'}

答案 2 :(得分:0)

尝试更改ID:to:id,如下所示:

before do
   put :update, :id => @user.password_reset_token
 end

答案 3 :(得分:0)

你实际上在使用describe "tests controller"吗?如果是这样,您可以尝试将其更改为describe TestsControllerdescribe UsersController(取决于哪个),以便RSpec知道哪个控制器正在测试中。

否则,您可以从异常消息中发布完整的回溯吗?