如何重构 JavaScript 和 HTML 请求\响应的测试代码?
我正在使用 Ruby on Rails 3.1.0 和 rspec-rails 2 gem。由于我必须测试同一控制器操作的 HTML 和 JavaScript 请求,并且有时这些请求会通过渲染不同视图文件或表现不同来响应,因此我想重构一些代码。
通常,在我的控制器文件中,我有:
def create
...
respond_to
format.html
format.js
end
end
此时,为了测试 JS 和 HTML 请求\响应,在我的规范文件中,我有两个不同的示例(一个例如,对于每种情况):
context "POST create" do
let(:user) { User.new }
it "should correctly respond to a JS request" do
xhr :post, :create
...
session[:user].should be_nil
flash[:notice].should be_nil
end
it "should correctly respond to a HTML request" do
post :create
...
session[:user].should be_nil
flash[:notice].should be_nil
end
end
我应该如何重构上面的代码?
I am using Ruby on Rails 3.1.0 and the rspec-rails 2
gem. Since I have to test both HTML and JavaScript requests for the same controller action and since sometime those responds by rendering different view files or behaving differently, I would like to refactor some code.
Generally, in my controller file I have:
def create
...
respond_to
format.html
format.js
end
end
At this time, in order to test both JS and HTML requests\responses, in my spec file I have two different examples (one example, for each case):
context "POST create" do
let(:user) { User.new }
it "should correctly respond to a JS request" do
xhr :post, :create
...
session[:user].should be_nil
flash[:notice].should be_nil
end
it "should correctly respond to a HTML request" do
post :create
...
session[:user].should be_nil
flash[:notice].should be_nil
end
end
How could\should I refactor the above code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
shared_examples_for
。希望这有帮助。
You could use
shared_examples_for
.Hope this helps.