testng rSpec保存或更新has_many关系

时间:2013-09-30 13:20:59

标签: ruby-on-rails-3 activerecord rspec

我有一个简单的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)model.model.create(blah)或model.model.new(blah)时,如何正确测试?

谢谢

2 个答案:

答案 0 :(得分:0)

我认为Score获取方法new,因此请尝试将代码更改为

Score.should_receive(:new).with(time_elapsed: 400)

答案 1 :(得分:0)

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

existing_user.scores.should have(1).item

但这个也有效

Score.count.should == 1