gpt4 book ai didi

ruby-on-rails - 使用 rspec 和 stub 对 Controller 进行故障测试

转载 作者:行者123 更新时间:2023-11-28 20:46:42 26 4
gpt4 key购买 nike

我很难用 before_filters、异常和一些 mocking 和 stubing 来测试我的 Controller 。这是 Controller :

before_filter :get_subject, :only => [:show, :edit, :update, :destroy, :update_field]
before_filter :user_has_to_belongs_to_subject_company, :only => [:show, :edit, :update, :destroy, :update_field]

def show
@messages = @subject.get_user_messages(current_user)
end

private

def get_subject
@subject = Subject.find(params[:id])
end

def user_has_to_belongs_to_subject_company
unless @current_user.company.eql?(@subject.company)
raise "Error: current_user does not belongs to subject's company"
end
end

这是我的规范文件:

require 'spec_helper'

describe SubjectsController do
describe "for signed users" do
before(:each) do
@current_user = Factory(:user)
sign_in @current_user
end

describe "for user belonging to subject's company" do
before(:each) do
@subject = mock_model(Subject)
Subject.stub!(:find).with(@subject).and_return(@subject)
@current_user.stub_chain(:company, :eql?).and_return(true)
@subject.stub!(:company)
end

it "should not raise an exception" do
expect { get :show, :id => @subject }.to_not raise_error
end
end

describe "for user not belonging to subject's company" do
before(:each) do
@subject = mock_model(Subject)
Subject.stub!(:find).with(@subject).and_return(@subject)
@current_user.stub_chain(:company, :eql?).and_return(false)
@subject.stub!(:company)
end

it "should raise an exception" do
expect { get :show, :id => @subject }.to raise_error
end
end
end
end

最后,这是错误信息:

SubjectsController for signed users for user belonging to subject's company should not raise an exception
Failure/Error: expect { get :show, :id => @subject }.to_not raise_error
expected no Exception, got #<RuntimeError: Error: current_user does not belongs to subject's company>
# ./spec/controllers/subjects_controller_spec.rb:19:in `block (4 levels) in <top (required)>'

感谢您的帮助!

最佳答案

我没有看到问题,但这里有一个重构建议。如果您发现自己比平时使用更多的模拟和 stub ,也许是时候重新考虑您的接口(interface)了。在这种情况下,您可以让您的 Controller 更瘦,让您的模型更胖。

# subjects_controller_spec.rb
describe "for user belonging to subject's company" do
before(:each) do
@subject = mock_model(Subject, :verify_user => true)
Subject.stub!(:find).with(@subject).and_return(@subject)
end

# subjects_controller.b
def user_has_to_belongs_to_subject_company
@subject.verify_user(@current_user)
end

# subject.rb
class Subject
def verify_user(user)
unless user.company.eql?(company)
raise "Error: current_user does not belongs to subject's company"
end

关于ruby-on-rails - 使用 rspec 和 stub 对 Controller 进行故障测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6385569/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com