【问题标题】:problem using mock_model to test controller使用 mock_model 测试控制器的问题
【发布时间】:2011-08-26 18:09:36
【问题描述】:

我正在尝试测试模型,但在创建模拟模型时遇到问题。

这是控制器的一部分:

def show
    @license = License.find(params[:id])

这是我的 rspec 的一部分:

it "can show a license" do
   mocks = (1..3).map { mock_model(License) }
   License.should_receive(:all).and_return(mocks)       
   post :show, {:id => 1}

但是,当我运行 rspec 时出现错误:

Failure/Error: License.should_receive(:all).and_return(mocks)
(<License(id: integer, license_id: string, location: string, format: string, license_type: string, language: string, context: string, licensor: string, licensee: string, resource: string, created_at: datetime, updated_at: datetime) (class)>).all(any args)
           expected: 1 time
           received: 0 times

另外,如果我让它工作,我如何更改许可证对象上的一个 ID。 'mocks[0].id = 5' 会起作用吗?

任何帮助将不胜感激。谢谢。

【问题讨论】:

  • 你在哪里执行License.all

标签: ruby-on-rails rspec tdd rspec-rails


【解决方案1】:

应该是License.should_receive(:find).with(1).and_return(mock) 这种情况下只有一个模拟就足够了:mock = mock_model(License)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-28
    • 2015-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-17
    • 1970-01-01
    相关资源
    最近更新 更多