问题
I am trying to create a mock object
and i am checking whether my method receives
the right param
and expected result.
Below is my spec
.
require 'spec_helper'
describe User do
let(:username) {"test@test.com"}
let(:password) {"123"}
let(:code) {"0"}
context "when signing in" do
it "should sign in" do
user = double("user")
expected_results = {
"token": "123"
}
allow(user).to receive(:login).with({email: username, password: password, code: code})
.and_return(expected_results)
expect(user.login).to eq(expected_results)
end
end
end
Is there a way to separate my json
from it
block and keep it outside?.
回答1:
You can use let
inside a context block to set the value of a variable for the examples nested within:
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
user = double("user")
allow(user).to receive(:login).with({email: username, password: password, code: code})
.and_return(expected_results)
expect(user.login).to eq(expected_results)
end
end
end
am i doing the right way of testing?
Not if you are testing the User#login
method. You should not set a stub if you are trying to test the logic of the method being stubbed. Instead, use a real model instance, perhaps using a factory, and omit the allow
step.
回答2:
You can use a before do
block in the context or before the context.
Here is the reference: https://www.relishapp.com/rspec/rspec-core/docs/hooks/before-and-after-hooks
来源:https://stackoverflow.com/questions/25273062/rspec-checking-for-json-response