0

我有一个简单UserScore类和一个IndexController

class User < ActiveRecord::Base
  has_many :scores
  attr_accessible :scores_attributes, :scores
  accepts_nested_attributes_for :scores
end

class Score < ActiveRecord::Base
  attr_accessible :time_elapsed
  belongs_to :user
end

我的 IndexController(简化版)

def setHighscore
  existing_user = User.find_by_random_token(session[:user][:random_token])
  existing_user.scores.new(time_elapsed: params[:time_elapsed])
  existing_user.save
end

我的规格

describe IndexController do
  it "appends a highscore to an existing user" do
    user = User.create!(valid_session[:user])
    existing_user = User.should_receive(:find_by_random_token).with(random_token).and_return(user)

     existing_user.scores.should_receive(:new).with(time_elapsed: 400)

     post :setHighscore, valid_params, valid_session
end

我收到了这个错误

RSpec::Mocks::MockExpectationError: (#<RSpec::Mocks::MessageExpectation:0x007fb4fa2b67c0>).new({:time_elapsed=>400})
    expected: 1 time with arguments: ({:time_elapsed=>400})
    received: 0 times with arguments: ({:time_elapsed=>400})

update_attribute(blah)当我执行ormodel.model.create(blah)或 model.model.new(blah)`时如何正确测试?

谢谢你

4

2 回答 2

0

我认为Scoregets方法new所以尝试将代码更改为

Score.should_receive(:new).with(time_elapsed: 400)
于 2013-09-30T13:26:56.503 回答
0

我不知道是什么导致了这个问题,但我最终使用了这两个术语之一:

existing_user.scores.should have(1).item

但这个也有效

Score.count.should == 1
于 2013-10-01T10:10:23.637 回答