15

我可以知道如何存根控制器创建方法中的方法吗?我需要为此编写规范,但我遇到了这些错误。我需要检查控制器中的创建方法必须在模型中创建新的公司记录之前执行 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)>'

公司控制器

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    
4

5 回答 5

25

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

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

当您在控制器中测试创建操作时,您可以存根“validate_fbid”

describe "post create" do
   ...
   CompaniesController.any_instance.stub(:validates_fbid).and_return('companyid')
   ...
end

希望能帮助到你。

于 2013-07-29T08:07:55.410 回答
6

当代码难以测试时,通常是因为它很复杂。

您应该以这种方式重构此代码:

  • 将验证逻辑移动到新的“服务类”中,该服务类仅负责在 Facebook 上进行公司验证
  • 这将使验证功能独立于 web 层并且容易测试
  • 为服务类制定规范,它将单独测试此代码(无控制器)
  • 清理逻辑控制器 - 你不想在你的控制器中有逻辑(经验法则:最大嵌套级别)
  • 控制器的规范也会更容易

控制器代码可能如下所示:

def create
  company = Company.new(params[:company])
  verified = FbCompanyVerifier.new.verify(company)

  if verified and company.save
    # success logic
  else
    # fail logic
  end
end
于 2013-07-29T09:55:06.087 回答
6

如果您正在测试控制器,您可以直接访问控制器:

controller.stub(:message) { 'this is the value to return' }
于 2014-08-28T00:07:52.447 回答
4

这是 Rspec 3 (3.3) 的推荐语法:

  • allow_any_instance_of(CompaniesController).to receive(:validates_fbid).and_return("companyid")

或者

  • expect_any_instance_of(CompaniesController).to receive(:validates_fbid).and_return("companyid")

来源:https ://relishapp.com/rspec/rspec-mocks/docs/working-with-legacy-code/any-instance

于 2015-09-29T23:58:51.473 回答
1

您可以存根controller方法:

allow(controller).to receive(...).with(...).and_return(...)
于 2022-01-24T13:38:19.033 回答