gpt4 book ai didi

ruby-on-rails - Rspec: Controller 中的 stub 方法

转载 作者:行者123 更新时间:2023-12-04 11:17:18 25 4
gpt4 key购买 nike

我可以知道如何 stub Controller 创建方法中的方法吗?我需要为此编写规范,但我遇到了这些错误。在模型中创建新公司记录之前,我需要检查 Controller 中的 create 方法必须执行 validate_fbid 方法。

错误:

1) Companies new company create with valid information#validate_fbid should have correct parameters and return value
Failure/Error: CompaniesController.create.should_receive(:validates_fbid).with(company)
NoMethodError:
undefined method `create' for CompaniesController:Class
# ./spec/requests/companies_spec.rb:38:in `block (5 levels) in <top (required)>'

2) Companies new company create with valid information#validate_fbid should fbid validation passed
Failure/Error: CompaniesController.create.stub(:validates_fbid).and_return('companyid')
NoMethodError:
undefined method `create' for CompaniesController:Class
# ./spec/requests/companies_spec.rb:43:in `block (5 levels) in <top (required)>'

公司 Controller
def create 
company = Company.new(params[:company])
verifyfbid = validate_fbid(company)

if verifyfbid != false
if company.fbid.downcase == verifyfbid.downcase
if company.save
@message = "New company created."
redirect_to root_path
else
@message = "Company create attempt failed. Please try again."
render 'new'
end
else
@message = "Company create attempt failed. Invalid facebook id."
render 'new'
end
else
@message = "Company create attempt failed. No such facebook id."
render 'new'
end
end

private
def validate_fbid(company)
uri = URI("http://graph.facebook.com/" + company.fbid)
data = Net::HTTP.get(uri)
username = JSON.parse(data)['username']
if username.nil?
return false
else
"#{username}"
end
end

请求/companys_spec.rb
context "#validate_fbid" do               
#validate fbid
let(:company){ Company.new(name:'Example Company', url: 'www.company.com', fbid: 'companyid', desc: 'Company desc' )}

it "should have correct parameters and return value" do
CompaniesController.create.should_receive(:validates_fbid).with(company)
.and_return('companyid')
end

it "should fbid validation passed" do
CompaniesController.create.stub(:validates_fbid).and_return('companyid')
company.fbid.should_not be_nil
company.fbid.should == 'companyid'
company.save
expect { click_button submit }.to change(Company, :count).by(1)
end
end

最佳答案

当它是测试用例的主题时,您不想 stub 该方法

context "#validate_fbid" do
#test the function here
#don't stub
end

当您在 Controller 中测试创建操作时,您可以 stub “validate_fbid”
describe "post create" do
...
CompaniesController.any_instance.stub(:validates_fbid).and_return('companyid')
...
end

希望能帮助到你。

关于ruby-on-rails - Rspec: Controller 中的 stub 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17918430/

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