【问题标题】:testng rSpec saving or update on a has_many relationtestng rSpec 保存或更新 has_many 关系
【发布时间】:2013-09-30 13:20:58
【问题描述】:

我有一个简单的 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)` 时如何正确测试?

谢谢

【问题讨论】:

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


    【解决方案1】:

    我认为Score 获取方法new 所以尝试将代码更改为

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

    【讨论】:

    • 好吧,我想得太复杂了。完成:expected: ({:time_elapsed=&gt;400}) got: ({:time_elapsed=&gt;"400"}, {}) 看起来不错,但是第二个哈希是从哪里来的?
    • 我从来没有遇到过这种情况,但是如果检查方法newdescription,它看起来是正确的。输入参数中有一些选项。
    • 我现在有了Score.should_receive(:new).with({:time_elapsed =&gt; 400}, {}),但仍然出现错误:NoMethodError: undefined method '[]=' for nil:NilClass。我是如何开始运行这个非常简单的东西的?
    • 我用类似的逻辑查看了我的测试。我有类似的测试,如果将其翻译成您的术语(示例):1.将控制器更改为existing_user.scores.build(time_elapsed: params[:time_elapsed]) 2.修改测试`Score.should_receive(:build).with({:time_elapsed=>400})
    • 谢谢.. 嗯.. 但现在它不再计数了:expected: 1 time with arguments: ({:time_elapsed=&gt;400}) received: 0 times with arguments: ({:time_elapsed=&gt;400})
    【解决方案2】:

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

    existing_user.scores.should have(1).item
    

    但这个也有效

    Score.count.should == 1
    

    【讨论】:

    • 您还可以准确地测试您的Score expect{ post(...) }.to change(Score, :count)的帖子更改计数
    • expect(post :setHighscore, valid_params, valid_session).to change(Score, :count) 为#`提出NoMethodError: undefined method call'
    • no :) 你应该期待改变计数的动作expect(post(:setHighscore, valid_params, valid_session)).to change(Score, :count)
    • 引发同样...NoMethodError: undefined method 'call' for #&lt;ActionController::TestResponse:0x007fd63fb022b0&gt;
    猜你喜欢
    • 1970-01-01
    • 2012-05-23
    • 2011-01-21
    • 2016-10-17
    • 2011-04-27
    • 2018-07-22
    • 2021-01-04
    • 2015-12-13
    • 1970-01-01
    相关资源
    最近更新 更多