Ruby on rails Rails/RSpec为什么可以';t我使用缩短的'quot;它的(:属性)";与Rails模型关联?
在RSpecRails中,我有一个名为“Customer”的activerecord模型。客户有很多“互动”。我最近花了不少时间调试一些东西。我让它工作,但我想出的答案对我来说真的没有意义 以下代码(利用RSpec的“主题属性”)不起作用:Ruby on rails Rails/RSpec为什么可以';t我使用缩短的'quot;它的(:属性)";与Rails模型关联?,ruby-on-rails,ruby,ruby-on-rails-3,unit-testing,rspec,Ruby On Rails,Ruby,Ruby On Rails 3,Unit Testing,Rspec,在RSpecRails中,我有一个名为“Customer”的activerecord模型。客户有很多“互动”。我最近花了不少时间调试一些东西。我让它工作,但我想出的答案对我来说真的没有意义 以下代码(利用RSpec的“主题属性”)不起作用: its(:interactions) { should_receive(:create) } 但这是可行的: it "should call the 'create' method on interactions" do subject.interac
its(:interactions) { should_receive(:create) }
但这是可行的:
it "should call the 'create' method on interactions" do
subject.interactions.should_receive(:create)
end
有人能解释为什么会这样吗?也许我误解了缩短方法语法的工作原理。我看过这些文件,但没有找到任何好的理由
以下是完整的代码:
describe Customer do
...other code ...
describe "#migrate_interactions" do
context "when a customer successfully migrates interactions from a lead" do
subject { FactoryGirl.create(:customer) }
let(:lead) { mock_model(Lead) }
before :each do
@lead_interaction = { :user_id => 1,
:interaction_type => 'phone',
:notes => 'test',
:created_at => Time.now
}
lead.should_receive(:interactions).and_return([stub(@lead_interaction)])
end
its(:interactions) { should_receive(:create) }
its(:interactions) { should_receive(:create).with(hash_including(@lead_interaction)) }
after { subject.migrate_interactions lead }
end
end
end
以及Customer.rb中的模型方法:
def migrate_interactions lead
raise ArgumentError unless lead.respond_to? :interactions
lead.interactions.each do |interaction|
self.interactions.create({ :user_id => interaction.user_id,
:interaction_type => interaction.interaction_type,
:notes => interaction.notes,
:created_at => interaction.created_at })
end
end
谢谢
----------编辑---------
我忘了包括在使用its(:interactions){…}语法时出现的错误。
以下是错误:
1) Customer#migrate_interactions when a customer migrates interactions from a lead interactions
Failure/Error: its(:interactions) { should_receive(:create) }
(#<RSpec::Core::ExampleGroup::Nested_2::Nested_6::Nested_3::Nested_1:0x0000000af10e78>).create(any args)
expected: 1 times
received: 0 times
# ./spec/models/customer_spec.rb:100:in `block (4 levels) in <top (required)>'
1)客户#迁移#客户从潜在客户迁移交互时的交互
失败/错误:其(:交互){should_receive(:create)}
(#)创建(任意参数)
预期:1次
收到:0次
#./spec/models/customer_spec.rb:100:in'block(4层)in'
您尝试执行的操作无法运行,因为RSpec的单行语法(例如,it{should do\u something}
)支持应该,但不支持应该接收。这是我从未想过要添加的东西,因为它不符合我对消息期望的方法,而且我认为它从未在功能请求中出现过
在开发中有一个新的语法选择,它是expect(object).to receive(message)
,这可能会打开it{should receive(message)}
,但我不确定(我不再运行该项目,也没有详细研究该代码)。如果你感兴趣,看看(并加入对话)
嗯,,
大卫