Rspec 检查返回值

use*_*655 4 testing rspec ruby-on-rails

我正在学习 rails rspec 中的测试。我有这部分测试:

subject(:service) { described_class.new() }
context 'when sth' do
  it 'should sth' do
    expect ( service.call(@params) ).to eq(0)
  end
end
Run Code Online (Sandbox Code Playgroud)

服务的方法调用返回编号。但我得到这样的东西:

失败:

 1) Module::Registration when sth should sth
 Failure/Error: expect ( service.call(@params) ).to eq(2)
 NoMethodError:
   undefined method `to' for 2:Fixnum
 # ./spec/module/registration_spec.rb:22:in `block (3 levels) in <module:Module>'

Finished in 2.48 seconds
1 example, 1 failure
Run Code Online (Sandbox Code Playgroud)

那么如何检查该方法使用 to 返回正确的“Number”变量?

Ste*_*fan 5

你必须删除之间的空间expect(

expect( service.call(@params) ).to eq(0)
#    ^^
Run Code Online (Sandbox Code Playgroud)

否则 Ruby 会单独计算表达式:

( service.call(@params) ).to
( 2 ).to
#=> undefined method `to' for 2:Fixnum
Run Code Online (Sandbox Code Playgroud)