Rails:如何测试state_machine?
请帮我。我很困惑。我知道如何编写模型的状态驱动行为,但我不知道应该在规范中编写什么...
我的 model.rb 文件看起来
class Ratification < ActiveRecord::Base
belongs_to :user
attr_protected :status_events
state_machine :status, :initial => :boss do
state :boss
state :owner
state :declarant
state :done
event :approve do
transition :boss => :owner, :owner => :done
end
event :divert do
transition [:boss, :owner] => :declarant
end
event :repeat do
transition :declarant => :boss
end
end
end
我使用 state_machine 宝石。
请给我看看课程。
Please, help me. I'm confused. I know how to write state-driven behavior of model, but I don't know what should I write in specs...
My model.rb file look
class Ratification < ActiveRecord::Base
belongs_to :user
attr_protected :status_events
state_machine :status, :initial => :boss do
state :boss
state :owner
state :declarant
state :done
event :approve do
transition :boss => :owner, :owner => :done
end
event :divert do
transition [:boss, :owner] => :declarant
end
event :repeat do
transition :declarant => :boss
end
end
end
I use state_machine gem.
Please, show me the course.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这个问题很老了,但我也有同样的问题。以 state_machine gem 为例:
我的解决方案是:
我正在使用:
The question is old, but I had the same one. Taking example from state_machine gem :
My solution was:
I was using:
state_machine_rspec gem 包含许多用于编写简洁规范的辅助方法。
这些 RSpec 匹配器将从高级别协助
state_machine
规范。从这里开始,我们需要为can_approve?
、can_divert?
和can_repeat?
的业务案例编写规范。The state_machine_rspec gem includes many helper methods for writing concise specs.
These RSpec matchers will assist with the
state_machine
specs from a high-level. From here, one needs to write the specs for the business cases forcan_approve?
,can_divert?
, andcan_repeat?
.我写了一个 RSpec 自定义匹配器。它允许以优雅而简单的方式测试状态流:检查一下
I have written a RSpec custom matcher. It allows to test state flow in elegant and simple way: check it out
不幸的是,我认为你需要对每个州进行测试 ->状态转换,这可能感觉像是代码重复。
幸运的是,我认为这通常适合集成测试。例如,支付系统的一个非常简单的状态机将是:
您可能仍然有上面的单元测试,但您可能还会有集成测试,例如:
这是很多手工放弃,但希望这是有意义的。我也不太习惯 RSpec,所以希望我没有犯太多错误。如果有更优雅的方法来测试这个,我还没有找到。
Unfortunately, I think you need to put a test for each state -> state transition, which might feel like code duplication.
Fortunately, I think this usually fits into integration testing. For instance, an extremely simple state machine for a payments system would be:
You might still have the unit tests as above, but you'll probably also have integration testing, something like:
That was a lot of handwaiving, but hopefully that makes sense. I'm also not super used to RSpec, so hopefully I didn't make too many mistakes there. If there's a more elegant way to test this, I haven't found it yet.