我正在使用 rspec 来测试使用声明了 attr_accessible 的模型的 Controller 。我不想测试 attr_accesible 是否正常工作(我的模型规范就是这样做的),但我确实想确保我的 Controller 没有进行批量分配。
具体来说,我有一个像这样的模型:
class Post < ActiveRecord::Base
attr_accessible :body
validates :body, :presence => true,
validates :user, :presence => true
belongs_to :user
end
和一个稍微调整的生成 Controller (删除了 xml 格式行):
def create
# this line keeps the rspec test mock happy
@post = Post.new(params[:post].merge(:user => current_user))
# Below are the correct lines of code for runtime for attr_accessible
# @post = Post.new(params[:post])
# @post.user = current_user
respond_to do |format|
if @post.save
format.html { redirect_to(@post, :notice => 'Post was successfully created.') }
else
format.html { render :action => "new" }
end
end
end
我使用模拟 Controller 进行了 rspec 测试,该测试通过了上述测试:
describe "POST create" do
describe "with valid params" do
it "assigns a newly created post as @post" do
Post.stub(:new).
with({'body' => 'hi there', 'user' => @user}) { mock_post(:save => true) }
post :create, :post => {'body' => 'hi there'}
assigns(:post).should be(mock_post)
end
end
end
我想要做的是更改 rspec 测试,以便在注释掉第一个 @post 行并取消注释以下两个 @post 行时正确验证 Controller 。这样,我将验证 Controller 是否可以与真实模型一起正常工作,但我可以继续使用模拟进行测试。我尝试了几种方法,但似乎一直在兜圈子(是的,我是 Rails 和 Rspect 的新手:p)
非常感谢!
最佳答案
检查批量分配。你需要复制它。因此在请求中发送错误的用户 ID
post :create, :post => {'body' => 'hi there', 'user_id' => '2'}
然后确保您创建的帖子具有 Controller 分配的 user_id(假设本例中其 id 不是 2)
assigns(:post)user_id.should be(current_user.id)
关于ruby-on-rails-3 - 如何编写不考虑批量分配的 rspec Controller 规范 model_mock,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5480936/