RSpec Controller测试,测试后期行动

时间:2016-06-04 21:16:49

标签: ruby-on-rails ruby rspec

现在我有一个subscriber控制器可以创建订阅者,但这不是我想要测试的。我在控制器中也有一个方法,在订阅服务器上添加1访问属性(我将发布代码),这是我想要测试的方法,但我不确定如何?我是rails和Rspec的新手,所以我很难理解这些概念。为了清楚起见,我会发布我的测试和控制器。

控制器:

def search
  @subscriber = Subscriber.new
end

def visit
  @subscriber = Subscriber.find_by_phone_number(params[:phone_number])
   if @subscriber
    @subscriber.visit =+ 1
    @subscriber.save
    flash[:notice] = "thanks"
    redirect_to subscribers_search_path(:subscriber)
  else
    render "search"
  end
end

TEST

it "adds 1 to the visit attribute" do
  sign_in(user)
  subscriber = FactoryGirl.create(:subscriber)
  visits_before = subscriber.visit
  post :create, phone_number: subscriber.phone_number
  subscriber.reload

  expect(subscriber.visit).to eq(visits_before)
end

错误消息:

enter image description here

正如您所看到的,这是我想要测试的方法。目前的测试不起作用,但我认为这可能有助于展示我的想法。希望这是足够的信息,如果你想看到别的什么,请告诉我?

3 个答案:

答案 0 :(得分:1)

由于您正在检查subscriber.visits,因此应将Subscriber更改为subscriber

expect { post :create, :subscriber => subscriber }.to change(subscriber, :visit).by(1)

visits是实例的方法,而不是类方法。

答案 1 :(得分:1)

我认为你可以这样做:

it 'adds 1 to the visit attribute' do
  # I'm assuming you need this, and you are creating the user before
  sign_in(user)
  # I'm assuming your factory is correct
  subscriber = FactoryGirl.create(:subscriber) 
  visits_before = subscriber.visit
  post :create, subscriber: { phone_number: subscriber.phone_number }
  subscriber.reload
  expect(subscriber.visit).to eq(visits_before)
end

答案 2 :(得分:0)

我认为您正在测试错误的方法。您已经声明您的create操作有效,因此无需在此处进行测试。单元测试都是关于隔离测试方法。

您编写的测试是测试post :create做了什么。如果您想测试visit方法是否有效,您需要执行以下操作:

describe "#GET visit" do
  before { allow(Subscriber).to receive(:find).and_return(subscriber) }
  let(:subscriber) { FactoryGirl.create(:subscriber) }

  it "adds one to the visit attribute" do
    sign_in(user)
    expect { get :visit }.to change(subscriber, :visit).by(1)
  end
end