Und*_*ker 3 ruby rspec ruby-on-rails ruby-on-rails-3
我有一个下面的规范,我是mocking我的用户模型stubbing及其方法.
require 'spec_helper'
describe User do
let(:username) {"test@test.com"}
let(:password) {"123"}
let(:code) {"0"}
context "when signing in" do
let(:expected_results) { {token:"123"}.to_json }
it "should sign in" do
expect(User).to receive(:login).with({email: username, password: password, code: code})
.and_return(expected_results)
end
end
end
Run Code Online (Sandbox Code Playgroud)
当我尝试运行我的测试用例时,我得到以下错误.
Failure/Error: expect(User).to receive(:login).with({email: username, password: password, code: code})
(<User (class)>).login({:email=>"test@test.com", :password=>"123", :code=>"0"})
expected: 1 time with arguments: ({:email=>"test@test.com", :password=>"123", :code=>"0"})
received: 0 times
Run Code Online (Sandbox Code Playgroud)
你误会是什么expect.
expect(x).to receive(:y)正在剔除该y方法x.
也就是说,它是关于该方法的论文.
一种描述这种方式的方法是,你正在"期望在实际运行代码时y调用方法x"
现在,你的规范没有调用任何实际的代码...它只是设置了期望...然后停止.
如果您正在测试该方法,login那么您需要不要期望它,但实际上将其称为真实.
例如 User.login(email: username, password: password, code: code)
你目前根本没有测试.只是你设置的存根,然后永远不会使用.