Rspec检查json响应
我正在尝试创建一个mock object
,我正在检查我的方法是否receives
正确的param
和预期的结果。
以下是我的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
有没有办法将我的json
与it
隔离并将其保持在外面?
您可以在上下文块中使用let
来为嵌套在其中的示例设置变量的值:
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
我在做正确的测试方式吗?
如果您正在测试User#login
方法,请不User#login
。 如果您尝试测试被存根方法的逻辑,则不应设置存根。 相反,使用真实的模型实例,可能使用工厂,并省略allow
步骤。
您可以在上下文中或上下文之前使用before do
块。
以下是参考: https : //www.relishapp.com/rspec/rspec-core/docs/hooks/before-and-after-hooks