我可以知道如何在控制器創建方法中存根方法嗎?我需要寫這個規範,但我得到了這些錯誤。我需要檢查控制器中的create方法,然後才能在模型中創建新的公司記錄之前執行validate_fbid方法。Rspec:在控制器中的存根方法
錯誤:
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)>'
CompaniesController
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
請求/ companies_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
'allow_any_instance_of(CompaniesController)。爲了接收(:validates_fbid)。and_return('companyid')'Rspec3 – ryan2johnson9