这个简单的控制器示例
describe 'create' do
it 'creates a panel' do
panel = SimplePanel.make!
TestingGroup.any_instance.should_receive(:add_panel!).with(panel, [SampleType::SERUM])
post :create, {
submission_id: submission.to_param,
testing_group_id: testing_group.to_param,
sample_type_ids: [SampleType::SERUM],
panel_ids: [panel.id]
}
end
end
产生以下结果
Failure/Error: post :create, {
#<TestingGroup:0x00000006685910> received :add_panel! with unexpected arguments
expected: (, [1])
got: (#<SimplePanel id: 266, name: "Some Simple Panel", description: nil, type: "SimplePanel", active: true, test_type_id: 1, species_id: 1, autonomous_panel: true, related_panel_id: nil, lock_version: 0, created_at: "2013-09-02 06:08:08", updated_at: "2013-09-02 06:08:08">, ["1"])
我的问题是面板对象(第一个参数)似乎完全没有超出测试结果的预期。
expected: (, [1])
它似乎不是null,或者是一个空字符串,它刚刚消失了。输出面板对象的值 在设定期望之前,没有任何惊喜,这是一个ActiveRecord对象 坚持到数据库。
将期望改为:
TestingGroup.any_instance.should_receive(:add_panel!).with(instance_of(SimplePanel), [SampleType::SERUM])
产生以下结果
Failure/Error: post :create, {
#<TestingGroup:0x00000006ff82e0> received :add_panel! with unexpected arguments
expected: (#<RSpec::Mocks::ArgumentMatchers::InstanceOf:0x00000006f4a208 @klass=SimplePanel(id: integer, name: string, description: text, type: string, active: boolean, test_type_id: integer, species_id: integer, autonomous_panel: boolean, related_panel_id: integer, lock_version: integer, created_at: datetime, updated_at: datetime)>, [1])
got: (#<SimplePanel id: 268, name: "Some Simple Panel", description: nil, type: "SimplePanel", active: true, test_type_id: 1, species_id: 1, autonomous_panel: true, related_panel_id: nil, lock_version: 0, created_at: "2013-09-02 06:22:17", updated_at: "2013-09-02 06:22:17">, ["1"])
这似乎和古怪一样。任何想法在这里发生了什么?
编辑:以下内容通常由SimplePanel.make创建!
attributes:
id: 2
name: Some Simple Panel
description:
type: SimplePanel
active: true
test_type_id: 1
species_id: 1
autonomous_panel: true
related_panel_id:
lock_version: 0
created_at: 2013-09-02 07:33:19.032650000 Z
updated_at: 2013-09-02 07:33:19.032650000 Z
答案 0 :(得分:1)
您的第二个参数应为[1]
(Fixnum
),而实际参数为["1"]
(String
)。也许第二个参数是你的规格失败了吗?
这并不能解释你的第一个例子中的奇怪输出......
答案 1 :(得分:1)
奇怪的输出是由SimplePanel模型中的description属性引起的。当RSpec为should_receive(..).with(..)
生成失败消息时,它使用args.collect {|arg| arg.respond_to?(:description) ? arg.description : arg.inspect}.join(", ")
格式化参数。这导致expected( ,[1])
中的空白,因为模拟模型上的描述为空白。
编辑:此问题已在当前版本的rspec中修复 - https://github.com/rspec/rspec-mocks/pull/417