我发现很难在控制器测试中存根模型的某些属性。我想确保尽可能少地存根。
编辑:我已经不再使用存根进行这种集成。我知道存根不会到达操作调用。现在正确的问题是:
如何在 Rails 控制器测试中使用 mocks 和 stub 来模拟某种状态?
所以我已经达到了以下内容:
规格
require 'spec_helper'
describe TeamsController do
let(:team) { FactoryGirl.create :team }
context "having questions" do
let(:competition) { FactoryGirl.create :competition }
it "allows a team to enter a competition" do
post(:enter_competition, id: team.id, competition_id: competition.id)
assigns(:enroll).team.should == team
assigns(:enroll).competition.should == competition
end
end
# ...
end
工厂
FactoryGirl.define do
factory :team do
name "Ruby team"
end
factory :competition, class: Competition do
name "Competition with questions"
after_create do |competition|
competition.
stub(:questions).
and_return([
"something"
])
end
end
factory :empty_competition, class: Competition do
name "Competition without questions"
questions []
after_create do |competition|
competition.stub(:questions).and_return []
end
end
end
生产代码
class TeamsController < ApplicationController
def enter_competition
@team = Team.find params[:id]
@competition = Competition.find params[:competition_id]
@enroll = @team.enter_competition @competition
render :nothing => true
end
end
class Team < ActiveRecord::Base
def enter_competition competition
raise Competition::Closed if competition.questions.empty?
enroll = Enroll.new team: self, competition: competition
enroll.save
enroll
end
end
当我运行测试时,该questions
属性是存在的nil
,因此在检查nil.empty?
.
为什么不使用存根以便正确使用该消息的状态?我预计@competition.questions
会是这样,[ "question" ]
但我得到了nil
.