Rspec:检测表单字段存在的辅助方法

时间:2014-03-18 01:24:34

标签: ruby-on-rails ruby rspec

如果填写了名为honeypot_detected?的表单字段的@params,我想测试我的控制器帮助方法birth_city是否为真。

我是否需要使用模拟测试?

helpers.rb:

def honeypot_detected?
  @params[:birth_city].present?
end

helpers_spec.rb

require 'spec_helper'

describe WindowWashers::Controllers::Shared::Helpers do
.
.
.
  before(:all) { @controller = ApplicationController.new }
    context "when honeypot_detected? is called" do
      it "returns true when birth_city is storing a value" do
        #Not sure how to represent :birth_city => 'Dallas     
        expect(honeypot_detected?).to be_true
      end
    end
  end
.
.
.
end

2 个答案:

答案 0 :(得分:1)

context "when honeypot_detected? is called" do
  it "returns true when birth_city is storing a value" do
    instance_variable_set(:@params, {:birth_city => "Dallas"})     
    expect(honeypot_detected?).to be_true
  end
end

答案 1 :(得分:1)

因为您正在检查存储在实例变量中的值you should be able to use assign to set it。我假设您的实例变量@params只是一个哈希,在这种情况下,您可能不需要像使用更复杂的对象那样使用测试双:

describe '#honeypot_detected?' do
  let(:honeypot_detected) { helper.honeypot_detected? }

  context 'when birth_city present in params' do
    before { assign(:params, { birth_city: "Dallas" }) } 
    it 'returns true' do
      expect(honeypot_detected).to be_true
    end
  end

  context 'when birth_city absent from params' do
    before { assign(:params, { foo: "bar" }) }
    it 'returns false' do
      expect(honeypot_detected).to be_false
    end
  end
end